从 C# 应用程序发送邮件

Sending mail from C# application

我正在尝试从我的 windows 表单申请中发送一封电子邮件。我看过很多类似的帖子,但 none 似乎有效。但是当我更改 gmail 中的设置以允许安全性较低的应用程序时,代码可以正常工作。但我不想让我的帐户容易受到此应用程序的攻击。如果我不允许安全性较低的应用程序,这是我得到的代码和错误。

MailMessage mail = new MailMessage("abc@gmail.com", "xyz@gmail.com", "Test Automation", "Did you receive this?");
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.Credentials = new NetworkCredential("abc@gmail.com", "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.

请帮忙!

P.S。 :我使用我的 gmail 创建了一个 outlook 帐户,当我输入 oulook 服务器和凭据时,代码有效。那么这是新的 gmail 安全更改的问题吗?其他类似的问题已经解决了,但在尝试了几乎所有解决方案后,我仍然遇到相同的错误。

如果你没有2因素

启用"Less Secure Apps"

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

如果您有 2 因素身份验证

你可以做一个"App Password"。转到下面的 ling 并添加一个自定义应用程序(只写你想要的任何名称,名称不重要只是用于你自己的 "bookkeeping")然后使用该密码作为密码。

client.Credentials = new NetworkCredential("From@gmail.com", "Generated Password");

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

注意: 如果你得到 "The setting you are looking for is not available for your account" 然后使用 "less secure app"