How to send Email using Gmail Server

November 2nd, 2012 | Posted by Nitesh Luharuka in .Net | General

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!

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

  • Michael

    I would definitely thank you with this great read through!! Bookmarked it.

  • Andrew

    To much code. better:
    SmtpClient smtp = new SmtpClient(“smtp.googlemail.com”, 587);
    smtp.Credentials = new NetworkCredential(“andriusa.aleksejunas@gmail.com”, “MySuperDuperPassword”);
    smtp.EnableSsl = true;
    MailMessage msg = new MailMessage(“andriusa.aleksejunas@gmail.com”, “andriusa.aleksejunas@gmail.com”, “subject”, “body”);
    smtp.Send(msg);

    • http://www.niteshluharuka.com Nitesh

      Andrew, You compressed my code :). Few things -
      1. It wont send HTML messages
      2. It does not add any email address as Cc or Bcc
      3. No Exception Handling
      4. If you want to customize the From name, you won’t be able to do with your bit of code.

  • Pingback: How to send Email using Gmail Server | Open Source Code | Scoop.it

  • new

    Nitesh,

    I am new to this, but have a server. What should I do next?

    • http://www.niteshluharuka.com Nitesh

      @new, Let me know where you’re stuck. If you use the above code and replace the credentials properly, you should be able to send emails.

  • Moshster

    @Andrew – When it makes no difference to runtime performance, readable code is preferable to compressed source code.

    • http://www.niteshluharuka.com Nitesh

      @Mohster, Agreed!

Support us!

If you like this site please help and make click on any of these buttons!

×