Search code examples
c#.netdockersmtpclient

System.Net.Mail.SmtpException: The server committed a protocol violation. On a dotnet 8 application running in a alpine image


I'm trying to update a blazor application from dotnet 6 to dotnet 8. Everything works fine, except for sending emails using the System.Net.Mail.SmtpClient using mailtrap as the smtp server.

using (var smtp = new SmtpClient(_smtpOptions.SmtpServer, _smtpOptions.SmtpPort.Value))
{
    smtp.EnableSsl = (_smtpOptions.SmtpPort.HasValue && _smtpOptions.SmtpPort.Value != 25);
    if (_smtpOptions.SmtpUserName is not null)
        smtp.Credentials = new NetworkCredential(_smtpOptions.SmtpUserName, _smtpOptions.SmtpPassword);
    
    await smtp.SendMailAsync(mailMessage);
}

It runs perfectly fine when debugging from Visual Studio on my local machine. But when running the application from the alpine image in kubernetes, the following exception occurs:

System.Net.Mail.SmtpException: The server committed a protocol violation. The server response was: 
   at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
   at System.Net.Mail.MailCommand.EndSend(IAsyncResult result)
   at System.Net.Mail.SendMailAsyncResult.SendMailFromCompleted(IAsyncResult result)
--- End of stack trace from previous location ---
   at System.Net.Mail.SendMailAsyncResult.End(IAsyncResult result)
   at System.Net.Mail.SmtpClient.SendMailCallback(IAsyncResult result)

Dockerfile:

...
FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine AS final
WORKDIR /app


COPY --from=build /app/publish .

ENV ASPNETCORE_URLS=http://+:80

ENTRYPOINT ["dotnet", "Educino.Webhost.dll"]

EXPOSE 80
EXPOSE 443

I assume this is a TLS problem?

I've this issue before when connecting to an old SQL database and was able to resolve this by adding the following to the dockerfile:

RUN sed -i 's/providers = provider_sect/providers = provider_sect\n\
ssl_conf = ssl_sect\n\
\n\
[ssl_sect]\n\
system_default = system_default_sect\n\
\n\
[system_default_sect]\n\
Options = UnsafeLegacyRenegotiation\n\
MinProtocol = TLSv1.2\n\
CipherString = DEFAULT@SECLEVEL=0/' /etc/ssl/openssl.cnf

But so far this hasn't worked out.

I also tried setting

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

Solution

  • Turns out the dotnet6 version had the same issue. Operations found out that it was a firewall issue.