Wednesday, October 20, 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.

No comments: