C#使用office365 smtp发送邮件

C# send email with office365 smtp

我正在使用 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...

编辑:

这可能是 SMTP 5.7.57 error when trying to send email via Office 365 的副本 但我在那里找不到解决方案,所以我想重新讨论。

问题中的代码是可以的。基本上就是需要在Office365账号上配置。

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

https://docs.microsoft.com/en-us/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 用于共享主机。