02/11/2012 by Nitesh

How to send Email using Gmail Server

I have seen many developers asking this questions and hence thought of writing this brief post. This post describes the code to send an email in C# using Gmail as mail server.

SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
smtpServer.Port = 587;
smtpServer.Host="smtp.gmail.com";
smtpServer.Credentials = new NetworkCredential("username@gmail.com", "PASSWORD");
smtpServer.EnableSsl = true;

MailMessage mail = new MailMessage();
mail.From = new MailAddress("username@gmail.com", "USER NAME");
mail.IsBodyHtml = true;
mail.To.Add("nitesh.luharuka@gmail.com"); //Sender's Email
mail.Cc.Add("nitesh.luharuka@gmail.com"); //Email address of person to be put in Cc
mail.Bcc.Add("nitesh.luharuka@gmail.com"); //Email address of person to be put in BCc
try
{
      mail.Subject = "Test Subject";
      String body = "Test Email using Gmail Server";
      mail.Body = body;
      smtpServer.Send(mail);      
}
catch (Exception)
{
      throw;
}

Hope you like it. Thanks for reading!

#.Net#C##Utilities