服务器违反协议服务器响应是

The server committed a protocol violation The server response was

我在没有对代码进行任何更改的情况下收到此错误。以前,它工作正常。

Depth: 0<br />Exception Type:System.Net.Mail.SmtpException<br />Exception: The server committed a protocol violation The server response was: <br />Inner Source: System<br />Stack Trace:    at System.Net.Mail.SendMailAsyncResult.End(IAsyncResult result)
   at System.Net.Mail.SmtpClient.SendMailCallback(IAsyncResult result)

我的代码:

private async Task SmtpClientSendMail(MailMessage mailMessage)
{
    using (SmtpClient smtpClient = new SmtpClient("smtp.office365.com"))
    {
        try
        {
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Port = 587;
            smtpClient.Credentials = new System.Net.NetworkCredential(emailUserNameCredentials, emailPasswordCredentials);
            smtpClient.EnableSsl = true;
            smtpClient.Timeout = 200000;
            await smtpClient.SendMailAsync(mailMessage);
        }
        catch (Exception ex)
        {

        }
    }
}

按照

中的建议

我已将其直接添加到我的 App.config 部分:

<system.net>
  <settings>
    <httpWebRequest useUnsafeHeaderParsing="true"/>
  </settings>
</system.net>

并且我也已将 <httpProtocol allowKeepAlive="false" /> 添加到 Web 配置中。尽管如此,我仍收到错误消息,并且未发送电子邮件。

有时,它可以正常工作而不会出现错误。为什么它不再像以前那样工作了?

可能确实是TLS版本问题,试试这个:

 System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

另请参阅:Enabling TLS 1.2 without changing code in .NET