May 19, 2012

Send SMTP mail using C# & .NET

Sending mail via web application or service, is now a days are very common. Most of user demands for email notifications or similar feature in their applications. There numerous of scripts are available to send mail. If you are using C# and .NET framework, and you want a code behind script to customise or create a dynamic mail using C# classes, you can use the following lines of code to generate and send SMTP mail.
using System.Net.Mail;


MailMessage mail = new MailMessage();
mail.To.Add("to-mail@gmail.com");
mail.From = new MailAddress("from@gmail.com");
mail.Subject = "Test Email";
string Body = "
Hello Navin,
Your online transaction id and password are as:
User Name: user-name@gmail.com
Password: user-name-password
";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.your-site.com";
smtp.Credentials = new System.Net.NetworkCredential("to-mail@gmail.com", "");
smtp.EnableSsl = true;
//smtp.Host = ConfigurationManager.AppSettings["SMTP"];
smtp.Send(mail);