Friday, October 24, 2008

Sending Email using Gmail Account live Sample

<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;<asp:TextBox ID="Txtmsg" runat="server" Height="231px" TextMode="MultiLine"
            Width="422px"></asp:TextBox><br />
        <asp:Label ID="lblMsg" runat="server" Width="362px"></asp:Label>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /></div>
    </form>
</body>
</html>

code behind
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Net;
using System.Net.Mail;


public partial class sndgooglemail : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        SmtpClient client = new SmtpClient();
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.EnableSsl = true;
        client.Host = "smtp.gmail.com";
        client.Port = 587;

        // setup Smtp authentication
        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("youruser@gmail.com", "Password");
        client.UseDefaultCredentials = false;
        client.Credentials = credentials;

        MailMessage msg = new MailMessage();
        msg.From = new MailAddress("youruser@gmail.com");
        msg.To.Add(new MailAddress("tomail@xxxx.com"));
        msg.To.Add(new MailAddress("to2@xxxxx.com"));
        msg.To.Add(new MailAddress("aaaaa@gmail.com"));

        msg.Subject = "This is a test Email subject";
        msg.IsBodyHtml = true;
        msg.Body = string.Format("<html><head></head><body><b>" + Txtmsg.Text + "Test HTML Email</b></body>");

        try
        {
            client.Send(msg);
            lblMsg.Text = "Message Sent.";
        }
        catch (Exception ex)
        {
            // lblMsg.ForeColor = Color.Red;
            lblMsg.Text = "Error occured while sending your message." + ex.Message;
        }

    }
}

No comments: