1

I am getting this error without making any changes to the code. Previously, it was working fine.

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)

My code:

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)
        {

        }
    }
}

As suggested in System.Net.WebException: The server committed a protocol violation

I have added this to my App.config directly in the section:

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

and I have added <httpProtocol allowKeepAlive="false" /> to web config as well. Still, I am getting the error and emails were not sent.

Sometimes, It is working without getting errors. Why does it no longer work as it used to be?

Shady
  • 73
  • 2
  • 10
  • I could be the email account send box is full or server is not response very quickly. I do not think it is your code. Talk to your ADMIN and see if there are any issue with Outlook. – jdweng Feb 02 '22 at 11:30
  • how do get quick responses from the server? @jdweng does email sending have any link with the Azure subscription. azure subscription related to sender email has been expired. Can it be the cause of this issue? – Shady Feb 02 '22 at 11:51
  • The issue is the connection between your smtp client and the Outlook server, not email destination. The port 587 gets forwarded to a proxy server to check credentials and most likely the TLS authentication failed. – jdweng Feb 02 '22 at 12:09

1 Answers1

6

Could indeed be TLS version problem, try this:

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

See also: Enabling TLS 1.2 without changing code in .NET

Poiter
  • 441
  • 2
  • 9
  • Thank you @Pointer. I changed the minimum TLS version in the azure web app but it didn't work. Do you have any idea why it doesn't; work? your solution worked – Shady Feb 03 '22 at 05:00