I want to send an email from my application and i have written following code for sending mail
MailMessage msg = new MailMessage();
msg.From = new MailAddress("mymailid");
msg.To.Add("receipientid");
msg.Subject = "test";
msg.Body = "Test Content";
msg.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("mymailid", "mypassword", "smtp.gmail.com");
client.Host = "smtp.gmail.com";
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.UseDefaultCredentials = true;
client.Send(msg);
I am running it on localhost so what mistake i am doing to send it.
When i send button it gives an error like
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
Code in Web.config file
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="smtpServer" value="smtp.gmail.com" />
<add key="EnableSsl" value = "true"/>
<add key="smtpPort" value="587" />
<add key="smtpUser" value="sender@gmail.com" />
<add key="smtpPass" value="mypassword" />
<add key="adminEmail" value="sender@gmail.com" />
</appSettings>
<system.net>
<mailSettings>
<smtp from="sender@gmail.com">
<network host="smtp.gmail.com" password="mypassword" port="587" userName="sender@gmail.com" enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
what should i do to solve this error and send mail??
Make sure that Access less secure app is allowed.
First check for gmail's security related issues. You may have enabled double authentication in gmail. Also check your gmail inbox if you are getting any security alerts. In such cases check other answer of @mjb as below
Below is the very general thing that i always check first for such issues
set it to false.
Note @Joe King's answer - you must set client.UseDefaultCredentials before you set client.Credentials
Ensure you set
SmtpClient.Credentials
after callingSmtpClient.UseDefaultCredentials = false
.The order is important as setting
SmtpClient.UseDefaultCredentials = false
will resetSmtpClient.Credentials
to null.Try it this way, I just made some light changes:
Also please show your app.config file, if you have mail settings there.
After turning less secure option on and trying other solutions, if you are still facing the same problem try to use this overload:
instead of:
I encountered the same problem even I set "UseDefaultCredentials" to false. Later I found that the root cause is that I turned on "2-step Verification" in my account. After I turned it off, the problem is gone.