我已经尝试了以上所有答案,但仍然使用Office 365帐户遇到此错误。当允许安全性较低的应用程序使用时,该代码似乎可以与Google帐户和smtp.gmail.com配合使用。
我可以尝试其他建议吗?
这是我正在使用的代码
int port = 587;
string host = "smtp.office365.com";
string username = "smtp.out@mail.com";
string password = "password";
string mailFrom = "noreply@mail.com";
string mailTo = "to@mail.com";
string mailTitle = "Testtitle";
string mailMessage = "Testmessage";
using (SmtpClient client = new SmtpClient())
{
MailAddress from = new MailAddress(mailFrom);
MailMessage message = new MailMessage
{
From = from
};
message.To.Add(mailTo);
message.Subject = mailTitle;
message.Body = mailMessage;
message.IsBodyHtml = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = host;
client.Port = port;
client.EnableSsl = true;
client.Credentials = new NetworkCredential
{
UserName = username,
Password = password
};
client.Send(message);
}
更新以及如何解决:
通过将Smtp客户端更改为Mailkit解决了问题。由于安全问题,现在不建议Microsoft使用System.Net.Mail Smtp客户端,而应该使用MailKit。使用Mailkit给我提供了更清晰的错误消息,使我可以理解找到问题(许可证问题)的根本原因。您可以通过以Nuget包的形式下载Mailkit。
阅读有关Smtp客户端的文档以了解更多信息:https ://docs.microsoft.com/es-es/dotnet/api/system.net.mail.smtpclient?redirectedfrom=MSDN&view=netframework-4.7.2
这是我用MailKit实现SmtpClient的方法
int port = 587;
string host = "smtp.office365.com";
string username = "smtp.out@mail.com";
string password = "password";
string mailFrom = "noreply@mail.com";
string mailTo = "mailto@mail.com";
string mailTitle = "Testtitle";
string mailMessage = "Testmessage";
var message = new MimeMessage();
message.From.Add(new MailboxAddress(mailFrom));
message.To.Add(new MailboxAddress(mailTo));
message.Subject = mailTitle;
message.Body = new TextPart("plain") { Text = mailMessage };
using (var client = new SmtpClient())
{
client.Connect(host , port, SecureSocketOptions.StartTls);
client.Authenticate(username, password);
client.Send(message);
client.Disconnect(true);
}