MailKit: The handshake failed due to an unexpected packet format

Viewed 657

I got exception when I try to connect to my SMTP server using MailKit SmtpClient. BUT my mails have been sent successfully if I use System.Net.Mail.SmtpClient with the same parameters!

The exception message: An error occurred while attempting to establish an SSL or TLS connection.

The inner exception message: The handshake failed due to an unexpected packet format.

Questions

  • Why does MailKit.Net.Smtp.SmtpClient throw exception but System.Net.Mail.SmtpClient doesn't? What is the difference between them?
  • How to fix it?

Code

Initialize the parameters required for mail sending:

var host = "myhost.com";
var port = 2525;
var from = "from@mydomain.com";
var to = "to@mydomain.com";
var username = "from@mydomain.com";
var password = "myPassword";
var enableSsl = true;

Sending mail using System.Net.Mail.SmtpClient:

var client = new System.Net.Mail.SmtpClient
{
    Host = host,
    Port = port,
    EnableSsl = enableSsl,
    Credentials = new NetworkCredential(username, password)
};

client.Send(from, to, "subject", "body"); // success.

But when I try to connect to the host using MailKit with the same host and port, I got the exception:

var mailKitClient = new MailKit.Net.Smtp.SmtpClient();
mailKitClient.Connect(host, port, enableSsl); // it throws the exception.
1 Answers

The problem is that you are connecting to a plain-text port and expecting SSL.

In MailKit, the true/false useSsl parameter is used to decide whether or not to connect in SSL mode or plain-text mode.

In System.Net.Mail, they don't support connecting in SSL mode, they only support upgrading a plain-text connection to SSL mode using the STARTTLS command once the connection has been established.

To overcome this, MailKit has a different Connect() method that takes an enum value SecureSocketOptions.

What you want is SecureSocketOptions.StartTls:

var mailKitClient = new MailKit.Net.Smtp.SmtpClient();
mailKitClient.Connect(host, port, SecureSOcketOptions.StartTls);
Related