Search code examples
c#smtpsendgridtcpclientsslstream

Handshake failed due to an unexpected packet format logging into a SMTP service


I am trying to connect to a SendGrid SMTP service over a secured connection. However, when I try to authenticate the TLS handshake, I get an System.IO.IOException saying "The handshake failed due to an unexpected packet format." I have confirmed the port is 587 and it should connect over TLS 1.2.

Note that I am not sending an email message and I do not want to use the SmtpClient.

        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        var server = "smtp.sendgrid.com";
        var port = 587;
        using (var client = new TcpClient()) {
            client.Connect(server, port);
            using (var stream = client.GetStream())
            using (var sslStream = new SslStream(stream)) {
                sslStream.AuthenticateAsClient(server);
                using (var writer = new StreamWriter(sslStream))
                using (var reader = new StreamReader(sslStream)) {
                    writer.WriteLine("EHLO " + server);
                    writer.Flush();
                    Console.WriteLine(reader.ReadLine());
                }
            }
        }

Solution

  • The problem is that you are attempting to upgrade the TCP connection to an SSL connection.

    SMTP port 587 is a plain-text port. It's possible to upgrade an SMTP connection on port 587 to SSL, but you need to send an EHLO command first and check that the server supports the STARTTLS extension. If it does, then you have to send a STARTTLS command and only then, after a successful response from the server, can you upgrade to the SSL connection using SslStream.AuthenticateAsClient().

    I should also point out that your current EHLO command is wrong - you should not be sending "EHLO " + server, you should be sending "EHLO " + localhost and the EHLO response from the server could be multi-line, so you'll need to handle that as well.