Dustin Horne

Developing for fun...

Sending Email With Google Mail and ASP.NET

If you're using Google Apps for your email you may want to send email through a Google Apps account from your website.  This is a process I've found to be poorly documented (the documentation can be difficult to find) and there are several examples of different implementations, some of which work and some do not.  You need to make sure you're using the correct outbound server, the correct port, and setting up the authentication credentials properly.  Here I'm going to show you how to make it work.

You can specify these options either directly in code or in your web.config file.  I would highly recommend setting the options in your web.config file but I'm going to show you how to do both just so you have an understanding of what options are actually being set.  Below is a quick method to send an email through your Google mail account:

using (var client = new SmtpClient("smtp.googlemail.com", 587))
	client.Credentials = new System.Net.NetworkCredential("address@yourdomain.com", "yourpassword");
	client.EnableSsl = true;
	var msg = new MailMessage("address@yourdomain.com", "toaddress@anotherdomain.com");
	msg.Body = "[YOUR EMAIL BODY HERE]";
	msg.Subject = "[Message Subject]";


As you can see in the above code, we're using smtp.googlemail.com as the outbound smtp server and connecting on port 587.  We're also using Network authentication and specifying your full email address and password.  We're also enabling SSL.  These settings are required to send mail through your google account.  Now that you have an idea of how it works, you can specify the majority of your settings in the <configuration /> section of your web.config file as follows:

      <smtp from="address@yourdomain.com" deliveryMethod="Network">
        <network host="smtp.googlemail.com" port="587" enableSsl="true"
            userName="address@yourdomain.com" password="yourpassword"/>

*Note:  enableSsl in the web.config smtp network configuration is only available for .NET 4.0 and above.  If you're using an earlier version, you will still need to specify it in code.

The actual mail sending code can then be rewritten as:

using (var client = new SmtpClient())
	var msg = new MailMessage()
			Subject = "[Message Subject]"