c# - SMTP 服务器需要安全连接或客户端未通过身份验证。请帮帮我
问题描述
我想从我的应用程序中发送一封电子邮件,以验证我用来注册但收到此错误的电子邮件。
The SMTP server requires a secure connection or the client was not authenticated. The server response
was: 5.7.57 SMTP;
我尝试进入我的 Gmail 设置并允许不太安全的应用程序打开,但它仍然无法正常工作。
用户控制器.cs
[NonAction]
public void SendVerificaitonLinkEmail(string email, string activationCode, string emailFor = "VerifyAccount")
{
var verifyUrl = "/User/" + emailFor + "/" + activationCode;
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, verifyUrl);
var fromEmail = new MailAddress("dotnetawesome@gmail.com", "Dotnet Awesome");
var toEmail = new MailAddress(email);
var fromEmailPassword = "**********"; // Replace with actual password
string subject = "";
string body = "";
if (emailFor == "VerifyAccount")
{
subject = "Your account is successfully created!";
body = "<br/><br/>We are excited to tell you that your Rockstar Awesome account is" +
" successfully created. Please click on the below link to verify your account" +
" <br/><br/><a href ='" + link + "'>" + link + "</a> ";
}
else if (emailFor == "ResetPassword")
{
subject = "Reset Password";
body = "Hi, <br/><br/> We got request for reset your account password. Please click on the link below to reset your password." +
"<br/><br/><a href = " + link + ">Reset Password link </a>";
}
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
{
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword);
};
using (var message = new MailMessage(fromEmail, toEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
client.Send(message); //
}
解决方案
我推荐使用MailKit
(https://github.com/jstedfast/MailKit)——代码维护得更好,更容易使用,而且作者实际上回应了 github 上的问题。内置的 .netSmtpClient
不再维护。
并不是说这会解决您的问题,但值得一试 - 您可以连接一个 smtp 客户端,然后调用身份验证并最终开始发送消息,从而更容易识别故障点。
示例MailKit
:
var message = new MimeKit.MimeMessage();
message.From.Add(new MimeKit.MailboxAddress("Name From", "YOU_FROM_ADDRESS@gmail.com"));
message.To.Add(new MimeKit.MailboxAddress("Name To", "YOU_TO_ADDRESS@gmail.com"));
message.Subject = "Subject Line";
message.Body = new MimeKit.TextPart("plain")
{
Text = @"Mail body message"
};
using var client = new MailKit.Net.Smtp.SmtpClient();
client.Connect("smtp.gmail.com", 587);
client.Authenticate("YOUR_GMAIL_NAME", "YOUR_PASSWORD");
client.Send(message);
client.Disconnect(true);
推荐阅读
- sql - SQL Server:条件语句逻辑
- r - 如何在 R 中找到模型上的特定点?
- python - 抓取错误:索引错误:在python中列出索引超出范围而(在csv上写入)
- c# - 无法在另一个方法中使用两种方法
- scala - 如何将动作优化器应用于发送到 SIRD 路由器的所有请求?
- amazon-web-services - Amazon Redshift UNLOAD 可以转换成 Parquet 或 Avro 格式吗?
- javascript - 如何使用 React Native 和 onPress 制作简单的动画?
- ios - 在 Tableview 标题中找到 UIButton 并更改按钮标题
- php - 当我单击添加到购物车按钮时会发生什么我在 laravel 中遇到了一些错误?
- arrays - 如何手动增加红宝石?