Thursday, December 26, 2013

Sending Email from Code behind using Gmail SMTP

Hi All,


Following is the simple snippet of code which you could use in your application to send email using gmail smtp.

Import following namespace
using System.Net.Mail;

Please replace the required mail credentials in order to get it running.


MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); //Store and get this from Config file

            mail.From = new MailAddress("Fromusername@gmail.com"); // Store and get this from config file
            mail.To.Add("ToUsername@gmail.com");
            mail.Subject = "Test Email using Gmail smtp";
            mail.Body = "This is the content of your email"+ Environment.NewLine + "Regards,"+ Environment.NewLine + "Narendra";
            SmtpServer.Port = 587; //Store and get this from config file
            SmtpServer.Credentials = new System.Net.NetworkCredential("username@gmail.com", "password"); // Replace this with your gmail credentials.
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);


Please Note:
Environment.NewLine - This adds line break.

Also you can use html string to set body, just set following flag to use html as body.
mail.IsBodyHtml = true;


Let me know if you have any questions.