Tuesday, August 19, 2014

Security Issue with using GMail SMTP to send email in MVC Application

I create a demo app to show the email confirmation in MVC today. Since i do not want to use the company mail server for demo.. then i create a test account in the gmail for this demo app.

I had use email account for test before, I did not encounter any issue. unfortunately i kept getting various error today. here is one of authentication issue.
 

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at

Source Error:


Line 107:                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
Line 108:
Line 109:                smtp.Send(myMessage);
Line 110:
Line 111:            }

Source File: C:\Users\Dan\Documents\Visual Studio 14\Projects\SecureEmailApp\SecureEmailApp\App_Start\IdentityConfig.cs    Line: 109 




the root cause of the issue is Gmail change the security setting to beef up the security. by default Access for Less secure Apps had been disabled. after i turned Access for less secure apps on. my demo goes very smooth. 


 

after you log into your gmail account and click on the link below to change the security setting for google account.

 https://www.google.com/settings/security/lesssecureapps


This snippet of code now works smoothly

var myMessage = new System.Net.Mail.MailMessage();
            myMessage.To.Add(message.Destination);
            myMessage.From = new System.Net.Mail.MailAddress(
                                "Joe@contoso.com", "Joe S.");
            myMessage.Subject = message.Subject;
            myMessage.Body = message.Body;
            myMessage.BodyEncoding = System.Text.Encoding.UTF8;


            using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient())
            {
                smtp.Host = "smtp.gmail.com";

                smtp.EnableSsl = true;

                NetworkCredential NetworkCred = new NetworkCredential("Mywebtest@gmail.com", "MyPassword1234");

                smtp.UseDefaultCredentials = false;

                smtp.Credentials = NetworkCred;

                smtp.Port = 587;

                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

                smtp.Send(myMessage);

            }










No comments:

Post a Comment