Send Mail in Asp.Net using GMAIL server


using System;
using System.Configuration;
using System.Data;
using System.Linq;
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.Xml.Linq;
using System.Net ;
using System.Net .Mail ;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(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("email id",
"password");

       client.UseDefaultCredentials = false;

       client.Credentials = credentials;



       MailMessage msg = new MailMessage();

       msg.From = new MailAddress("email id");

       msg.To.Add(new MailAddress("email id"));



       msg.Subject = "This is a test Email subject";

       msg.IsBodyHtml = true;

       msg.Body = string.Format("Test HTML Email");



       try
       {

           client.Send(msg);

           lblMsg.Text = "Your message has been successfully sent.";

       }

       catch (Exception ex)
       {

           // lblMsg.ForeColor = Color.Red;

           lblMsg.Text = "Error occured while sending your message." +
ex.Message;

       }
    }
}

0 comments:

Post a Comment