Saturday, February 21, 2015

Using GMail as email service from Azure

Following these posts:

I have successfully setup my Azure hosted ASP.NET MVC project to send email via SendGrid. But, SendGrid is a bit slow, which is irritating when the email is for registration confirmation - which I want to be as fast as possible, so if a user registers, that user will get an email within a minute or faster to confirm his/her email to complete registration. If the use must wait longer than that, chances are that the registration will never be continued and finished. So I wanted to use a faster email service - why not GMail?

Here is the SendGrid code:
  1. private static async Task SendGridSendAsync(string to, string from, string subject, string body)
  2. {
  3. var myMessage = new SendGridMessage();
  4. myMessage.AddTo(to);
  5. myMessage.From = new System.Net.Mail.MailAddress(
  6. "my.service.email.address@gmail.com", "my.service");
  7. myMessage.Subject = subject;
  8. myMessage.Text = body;
  9. myMessage.Html = body;
  10.  
  11. var credentials = new NetworkCredential(
  12. "sendGridAccount", "sendGridPassword"
  13. );
  14.  
  15. // Create a Web transport for sending email.
  16. var transportWeb = new SendGrid.Web(credentials);
  17.  
  18. // Send the email.
  19. if (transportWeb != null)
  20. {
  21. await transportWeb.DeliverAsync(myMessage);
  22. }
  23. else
  24. {
  25. Trace.TraceError("Failed to create Web transport.");
  26. await Task.FromResult(0);
  27. }
  28. }
Here is the GMail code:
  1. private static async Task GmailSendAsync(string to, string from, string subject, string body)
  2. {
  3. var sentFrom = (string.IsNullOrEmpty(from) ? "my.service.email.address@gmail.com" : "my.service");
  4.  
  5. // Configure the client:
  6. System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.gmail.com");
  7.  
  8. client.Port = 587;
  9. client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
  10. client.UseDefaultCredentials = false;
  11.  
  12. // Creatte the credentials:
  13. System.Net.NetworkCredential credentials = new NetworkCredential(
  14. "gmailAccount", "gmailPassword"
  15. );
  16. client.EnableSsl = true;
  17. client.Credentials = credentials;
  18.  
  19. // Create the message:
  20. var mail = new System.Net.Mail.MailMessage(sentFrom, to);
  21. mail.Subject = subject;
  22. mail.Body = body;
  23.  
  24. await client.SendMailAsync(mail);
  25. }
-- read more and comment ...