Sending Email In C# Through Gmail

posted on 11/12/07 at 10:33:55 pm by Joel Ross

I've recently written about how Tourney Logic has switched all of it's email over to Google Apps. Well, one side effect of that is that our applications had to be updated to send our email through the Google servers rather than the email servers we were using.

I was actually able to do it with only one minor code change and a change to the web.config. First, the web.config mail settings section:

   1:  <>
   2:     <mailSettings>
   3:        <smtp from="">
   4:           <network host="" port="587" userName="" password="pwd" />
   5:        </smtp>
   6:     </mailSettings>
   7:  </>

Obviously, substitute your own email address and password, but once you've done that, this configuration should work. One shortcoming I see with the configuration is that it doesn't allow us to specify the use of SSL, which Gmail requires. So that's the one code change:

   1:  System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
   2:  client.EnableSsl = bool.Parse(ConfigurationManager.AppSettings["MailSSL"]);

To shield ourselves from code changes in the future, we added an app setting to determine if we want SSL. That way, in the future, if we move back to a non-Gmail account to send mail from, we just change the mailSettings section, change MailSSL to be false, and we're good to go.

Just a note that I did try port 465 (another port supported by Gmail) to send mail initially, and got a timeout every time, so I switched to 587, and mail started going through just fine.

Tags: | |

Categories: Development, C#