SamD SamD - 14 days ago 7
ASP.NET (C#) Question

SMTP server Error in ASP.NET project

Im Develop the Asp.net web application. im Add the Email part,
i had a following error cant sent the email.

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


Im try to fix it more than 5 hours, but i cant fix this, i was refer all of Stack overflow question



class

public static void SendEmail(string receientEmail, string subject, string body) {
//Email
using (MailMessage mailMessage = new MailMessage()) {

mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["UserName"]);

mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(receientEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
smtp.Send(mailMessage);
}





WebConfig

<appSettings>
<add key="AdminLoginID" value="admin"/>
<add key="AdminPassword" value="123"/>
<!--Email Setting-->
<add key ="Host" value="smtp.gmail.com"/>
<add key ="EnableSsl" value="true"/>
<add key ="UserName" value="cafe****@gmail.com"/>
<add key ="Password" value="****"/>
<add key ="Port" value="587"/>
</appSettings>

Answer

For sending mail using gmail smtp server, you have to first set access to less secure apps. You can do that here from google's settings. If you don't do that, you get "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required." error.

You can not turn on access to less secure apps if google two step verification is enabled. For sake of code simplicity(Prone to risk), I suggest you should turn off two step verification on your google account and then turn on access to less secure apps.

Refer this question to know more about this.

The only problem with your code is smtp.UseDefaultCredentials = true;. If you remove that line then, your code should work with other smtp servers which do not have two step verification enabled.