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:
        private static async Task SendGridSendAsync(string to, string from, string subject, string body)
        {
            var myMessage = new SendGridMessage();
            myMessage.AddTo(to);
            myMessage.From = new System.Net.Mail.MailAddress(
                                "my.service.email.address@gmail.com", "my.service");
            myMessage.Subject = subject;
            myMessage.Text = body;
            myMessage.Html = body;

            var credentials = new NetworkCredential(
                       "sendGridAccount", "sendGridPassword"
                       );

            // Create a Web transport for sending email.
            var transportWeb = new SendGrid.Web(credentials);

            // Send the email.
            if (transportWeb != null)
            {
                await transportWeb.DeliverAsync(myMessage);
            }
            else
            {
                Trace.TraceError("Failed to create Web transport.");
                await Task.FromResult(0);
            }
        }
Here is the GMail code:
        private static async Task GmailSendAsync(string to, string from, string subject, string body)
        {
            var sentFrom = (string.IsNullOrEmpty(from) ? "my.service.email.address@gmail.com" : "my.service");

            // Configure the client:
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.gmail.com");

            client.Port = 587;
            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;

            // Creatte the credentials:
            System.Net.NetworkCredential credentials = new NetworkCredential(
                 "gmailAccount", "gmailPassword"
                 );
            client.EnableSsl = true;
            client.Credentials = credentials;

            // Create the message:
            var mail = new System.Net.Mail.MailMessage(sentFrom, to);
            mail.Subject = subject;
            mail.Body = body;

            await client.SendMailAsync(mail);
        }

No comments: