Wednesday, June 19, 2013

How to send email using C#

C# provides many built in exiting features to make developer life easy. SmtpClient class is one of them. SmtpClient has every thing that we need to send email from our application.

Namespace : System.Net

The following program illustrate how to send email using SmtpClient from our Asp.Net application.

SmtpClient s = new SmtpClient();
s.Host = "smtp host"; // here enter smtp host, for google = smtp.gmail.com
s.Port = 25;
s.UseDefaultCredentials = false;
MailMessage m = new MailMessage();
m.To.Add("xxx@xxx.com"); // enter reciepent email address
m.From = new MailAddress("xxx@xxx.com"); // enter sender email address
m.Subject = "xxxx"; // mail subject
m.Body = "xxxxxxxxx"; // mail body
m.Priority = MailPriority.High;
s.Credentials = new NetworkCredential("userid", "password"); // for gmail user id is your email address, password is your gmail password.
//s.EnableSsl = true; // for gmail remove the comment
s.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
            s.Send(m);
            Response.Write("done")
}
catch (Exception ex)
{
            Response.Write(ex.Message.ToString());
}
 


Some times the above code gives an error "Require authenticaton" after giving all correct details. It means your smtp server require mail body level authentication. In such case use the following code



Namespace : System.Web.Mail

MailMessage Message = new MailMessage();
Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "xxx@xxx.xxx"); // user id (email)
Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "xxx"); // password
Message.To ="xxx@xxx.xxx";
Message.From ="xxx@xxx.xxx";
Message.Subject = "xxx";
Message.Body = "XXXXXXXXXXX";
try
{
            SmtpMail.SmtpServer = "xxx.xxx.xxx.xxx";
            SmtpMail.Send(Message);
}
catch (System.Web.HttpException ehttp)
{
            Response.Write(ehttp.Message.ToString());
}