Thursday, December 20, 2012

Sending Email via GMail SMTP using C#

I recently availed of a cloud server over at Rackspace.  Since the company does not provide a public SMTP server for their clients, I  had two options -- install my own or, as my brother-in-law suggested, use GMail for outgoing SMTP.  The latter sounded a lot more appealing as maintaining an SMTP server is not a simple task.

I searched around the Internet for sample code and it turned out to be much simpler than I expected with .NET because the System.Net.Mail class structure already has all the stuffs needed to implement the security stuffs.  It just looks something like this:

System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("dick.chiang@gmail.com", "mypassword");

System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress("dick.chiang@gmail.com", "Dick Chiang");
System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress("someguy@yahoo.com");
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to);
message.Subject = "Sample GMail Message";
message.Body = "Hello world from GMail!";
client.Send(message);

No comments: