SyntaxHighlighter

Tuesday, 19 October 2010

Sending Email using ASP.NET via Google Apps Mail / GMail

I have recently moved all my hosting to go through Google Apps and it is sweet :)

This meant that I needed to modify my emailing routine in various .NET apps. A lot of this can be done via the Web.Config, but due to various reasons, I need to control it in code.

So configure your MailMessage object as per usual. I have added msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; to mine, which could prove to be useful. Then configure your SmtpClient a follows:

SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.EnableSsl = true;
smtp.Timeout = 10000;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("email@mydomain.com", "my-password");
smtp.Send(msg);

Now a lot of articles I read suggested that you need to use port number 587 for the SmtpClient. When I did, I got the following error:

Request for the permission of type 'System.Net.Mail.SmtpPermission' failed

So I tried without declaring it and it worked just fine :)

A point worth noting: Make sure the account you are sending the email through is the same account that you are sending from.