Wednesday, August 18, 2010

How to send an email via GMail using .NET

It’s really easy to use GMail as an SMTP client:

public class GoogleSmtpTest
{
    public void SendEmailViaGmail()
    {
        var message = new MailMessage(
            "xxx@gmail.com",
            "yyy@joebloggs.com", 
            "Hi via Google SMTP",
            "some body");

        var client = new SmtpClient("smtp.gmail.com")
        {
            EnableSsl = true,
            Port = 587,
            Credentials = new NetworkCredential("xxx@gmail.com", "xxx's gmail password")
        };

        client.Send(message);
    }
}

The only thing to note is that the SSL port given in the documentation (465) doesn’t seem to work, but the TLS one (587) works fine.

3 comments:

  1. Do you know if it also works with Google Apps accounts? If you don't I plan to give it a go soon, so I'll get back either way.

    ReplyDelete
  2. Yup, works fine with Google Apps for Domains.

    ReplyDelete
  3. I like that- nice. Another thing many people don't realise is you can get the .NET mail API to write the mail out to a file, which is damn handy when testing:

    http://msdn.microsoft.com/en-us/library/system.net.mail.smtpdeliverymethod.aspx

    ReplyDelete

Note: only a member of this blog may post a comment.