Search code examples
c#winformsemailgmailvisual-studio-2015

Sending mail from C# application


I am trying to send out an email from my windows form application. I have seen a lot of similar posts, but none seem to work. But when I change my settings in gmail to allow less secure apps, the code works. But I don't want to make my account vulnerable for this application. Here's the code and error I get if I don't allow less secure apps.

MailMessage mail = new MailMessage("[email protected]", "[email protected]", "Test Automation", "Did you receive this?");
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.Credentials = new NetworkCredential("[email protected]", "password");
client.EnableSsl = true;
client.Send(mail);
MessageBox.Show("Mail Sent", "success");

An unhandled exception of type 'System.Net.Mail.SmtpException' occurred in System.dll

Additional information: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

Please help!

P.S. : I created an outlook account using my gmail and when i put in the oulook server and credentials, the code works. So is it the issue with new gmail security changes? Other similar questions have their problem solved, but I keep having the same errors after trying pretty much every solution.


Solution

  • If you don't have 2 factor

    Enable "Less Secure Apps"

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

    If you have 2 factor authentication

    You can make an "App Password". Go to the ling below and add a custom app (just write any name you want, name not important just used for your own "bookkeeping") then use that password as the password.

    client.Credentials = new NetworkCredential("[email protected]", "Generated Password");

    https://security.google.com/settings/u/1/security/apppasswords

    NOTE: If you get "The setting you are looking for is not available for your account" then use "less secure app"