在 asp.net 核心应用程序中尝试使用 SmtpClient 发送电子邮件时出错

Getting an error when trying send an email using SmtpClient in asp.net core application

我正在尝试从 asp.net 核心应用程序发送电子邮件,但我一直收到一条错误消息

SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 Client not authenticated to send mail. [JN2P275CA0038.ZAFP275.PROD.OUTLOOK.COM]

我也试过检查防火墙规则和增加超时,但没有帮助,所以我不确定哪里出了问题

这是我发送电子邮件的代码

   SmtpClient client = new SmtpClient("smtp.office365.com")
                    {
                        //Port = 587, //outlook port 587
                        Port = 587, 
                        EnableSsl = true,
                        //UseDefaultCredentials
                        UseDefaultCredentials = false,
                        TargetName = "STARTTLS/smtp.office365.com",
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Credentials = new NetworkCredential("myemail@myemails.com","password"),
                    };

                    MailMessage message = new MailMessage()
                    {
                        From = new MailAddress("myemail@myemails.com"),
                        Subject = "New Requisition",
                        Body = "New requisition has been created:" + " " + requisition.RequisitionNo,
                        IsBodyHtml = true,
                    };

                    message.To.Add(SubmissionNotfication.To);
                    //message.CC.Add(SubmissionNotfication.Cc);
                    //var attachment = new System.Net.Mail.Attachment(filePath); //Attachment(string fileName, string mediaType) 
                    //message.Attachments.Add(attachment);
                    client.Send(message);
                }
        

看看How to set up an application to send email using Microsoft 365 or Office 365

您可能必须使用 MX 端点作为发送域并尝试端口 25

SmtpClient client = new SmtpClient("yourorganisation.mail.protection.outlook.com")
{
    Port = 25, 
    EnableSsl = true,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential("myemail@myemails.com","password"),
};

您遇到上述错误消息的原因可能有几个

  1. 电子邮件用户名和密码不正确
  2. SSL 设置。确保在通过您的应用程序发送电子邮件时启用 SSL 安全性
  3. 你的端口问题。请确保您的 ISP 未阻止端口 25 或 587。您可以使用 telnet 进行检查。

您可能需要查看有关使用 outlook 发送电子邮件的教程。如果你使用的是Gmail,那么你可以参考这个posthttps://dotnetblog.asphostportal.com/using-gmail-to-send-email-in-asp-net-core/