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 =
s.Port = 25;
s.UseDefaultCredentials = false;
MailMessage m = new MailMessage();
m.To.Add(""); // enter reciepent email address
m.From = new MailAddress(""); // 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;
catch (Exception ex)

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("", "1");
Message.Fields.Add("", ""); // user id (email)
Message.Fields.Add("", "xxx"); // password
Message.To ="";
Message.From ="";
Message.Subject = "xxx";
Message.Body = "XXXXXXXXXXX";
            SmtpMail.SmtpServer = "";
catch (System.Web.HttpException ehttp)