当前位置: 首页 > 知识库问答 >
问题:

C#SMTP MailMessage接收错误“5.7.57 SMTP;客户端未通过身份验证,无法在发送邮件期间发送匿名邮件”

苏俊友
2023-03-14

我目前拥有的代码是:

    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上。我们可能需要稍后更改特定地址,但它们可能配置相同。

但是,每当我尝试运行客户端.发送(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的,或者将UseDefault凭据EnableSssl切换为true或false。但是我总是看到同样的错误。我还遗漏了什么吗?

共有1个答案

皇甫喜
2023-03-14

我在这个网站的其他地方找到了一个示例代码块,并用它替换了我所有的代码

函数名和参数是相同的,但是下面是我用它的正文替换的。

 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链接替换主机值,以及记住添加一个我以前没有的目标名称,这两种方法都成功解决了授权问题(我之前已经确认这不是我们技术支持的凭证问题)。

 类似资料: