C# 使用 Office365 SMTP 发送电子邮件

3

我正在使用C#从本地计算机发送电子邮件,但在执行以下测试代码时遇到错误。

C# 代码:

protected void SendEmail(string emailAddres)
{
    SmtpClient smtp = new SmtpClient();

    MailMessage mail = new MailMessage()
    {
        To = { new MailAddress(emailAddres) },
        From = new MailAddress("email@email.com", "fromEmail"),
        Subject = "Subject of a test email!",
        IsBodyHtml = true,
        Body = "Test body email.",
        BodyEncoding = System.Text.Encoding.UTF8,
        SubjectEncoding = System.Text.Encoding.UTF8
    };

   try
   {
       smtp.Send(mail);
       lblResultEmail.Text = "Message Sent Succesfully";
       lblResultEmail.ForeColor = System.Drawing.Color.Green;
   }
   catch (Exception ex)
   {
       lblResultEmail.Text = ex.ToString();
       lblResultEmail.ForeColor = System.Drawing.Color.Red;
   }
}

Web.config 文件中,我添加了以下内容:
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network host="smtp.office365.com" port="587" defaultCredentials="false" enableSsl="true"  
                 userName="email@email.com" password="ThisPwd" targetName="STARTTLS/smtp.office365.com"
        />
      </smtp>
    </mailSettings>
  </system.net>

错误信息:

System.Net.Mail.SmtpException:SMTP 服务器要求安全连接,或客户端未进行身份验证。服务器响应为:5.7.57 SMTP;在MAIL FROM期间未经身份验证的客户端无法发送匿名邮件[AM0PR05CA0077.eurprd05.prod.outlook.com] at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response) at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message) at...

编辑:

这可能是通过Office 365发送电子邮件时出现SMTP 5.7.57错误的重复问题。但我在那里找不到解决方案,因此我想重新打开讨论。


与此同时,我发现我们需要使用MX记录siteX.mail.protection.outlook.com,但我还没有找到实现它的方法。https://answers.microsoft.com/en-us/msoffice/forum/msoffice_outlook-mso_winother/client-was-not-authenticated-to-send-anonymous/d405bcb0-f40c-42fa-b1b2-477597100123。由于某种原因,该MX记录在端口587上无法访问,当我配置端口25时,它能够建立连接,但随后Microsoft阻止了我的公共IP发送电子邮件。 - Dieter
仍然没有找到解决方案。当网站在启用了 https 的 Azure 应用服务和免费的应用服务计划上部署时,我会收到相同的错误。 - Dieter
不需要MX记录。请查看下面的答案。 - Dieter
1个回答

4

问题中的代码是正确的。基本上需要在Office365帐户上进行配置。

查阅以下Microsoft文档以获取更多信息。

https://learn.microsoft.com/zh-cn/exchange/clients-and-mobile-in-exchange-online/authenticated-client-smtp-submission#enable-smtp-auth-for-specific-mailboxes

如果你已经购买了GoDaddy的Office365电子邮件账户,请向他们请求启用SMTP AUTH功能。他们会为您启用它,但是除非您使用虚拟专用服务器,否则您仍然无法在其托管中使用Office365 smtp服务器,因为GoDaddy会阻止共享托管的587端口。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接