我目前的代码是:
public void SendEmail(string to, string cc, string bcc, string subject, string body, string attachmentPath = "", System.Net.Mail.MailPriority emailPriority = MailPriority.Normal, BodyType bodyType = BodyType.HTML)
{
try
{
var client = new System.Net.Mail.SmtpClient();
{
client.Host = "smtp-mail.outlook.com";
client.Port = 587;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential("[my company email]", "[my password]");
client.Timeout = 600000;
}
MailMessage mail = new MailMessage("[insert my email here]", to);
mail.Subject = subject;
mail.Body = body;
client.Send(mail);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我尝试发送到的电子邮件地址托管在Office 365的Outlook上。我们可能必须稍后更改特定地址,但它们可能配置相同。
但是,每当我尝试运行client.Send(mail);
命令时,我都会收到同样的错误。错误的全文是:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
我尝试了一些不同的东西,比如在25到587之间切换端口,将主机更改为Office365,或者将UseDefaultCredentials
和EnableSssl
切换为true或false。但我总是看到同样的错误。还有什么我想念的吗?
我在这个网站的其他地方找到了一个示例代码块,并且用它替换了我所拥有的一切代码块。
函数名称和参数是相同的,但这里是我用它替换它的主体。
var _mailServer = new SmtpClient();
_mailServer.UseDefaultCredentials = false;
_mailServer.Credentials = new NetworkCredential("my email", "my password");
_mailServer.Host = "smtp.office365.com";
_mailServer.TargetName = "STARTTLS/smtp.office365.com";
_mailServer.Port = 587;
_mailServer.EnableSsl = true;
var eml = new MailMessage();
eml.Sender = new MailAddress("my email");
eml.From = eml.Sender;
eml.To.Add(new MailAddress(to));
eml.Subject = subject;
eml.IsBodyHtml = (bodyType == BodyType.HTML);
eml.Body = body;
_mailServer.Send(eml);
我不确定,但我认为用smtp Office 365链接而不是outlook一个替换Host值,以及记住添加我之前没有的目标名称,两者都做了诀窍并解决了授权问题(我之前已经确认这不是我们技术支持的证书问题)。