The handshake failed due to an unexpected packet format

Most likely your server requires explicit SSL. So first try to connect without SSL:

// C#

client.Connect("imap.example.com");
' VB.NET

client.Connect("imap.example.com")

Then, before logging-in, start explicit SSL negotiation. The command name differs for different protocols:

In case of IMAP:

// C#

client.StartTLS();
' VB.NET

client.StartTLS()

In case of POP3:

// C#

client.STLS();
' VB.NET

client.STLS()

In case of SMTP:

// C#

client.StartTLS();
' VB.NET

client.StartTLS()

Now, your connection is secured.

Remember that you can ignore SSL certificate errors using ServerCertificateValidate event:

// C#

static void Validate(
    object sender,
    ServerCertificateValidateEventArgs e)
{
    const SslPolicyErrors ignoredErrors =
        SslPolicyErrors.RemoteCertificateChainErrors |
        SslPolicyErrors.RemoteCertificateNameMismatch;

    if ((e.SslPolicyErrors & ~ignoredErrors) == SslPolicyErrors.None)
    {
        e.IsValid = true;
        return;
    }
    e.IsValid = false;
}

client.ServerCertificateValidate += Validate;
' VB.NET

Private Sub ValidateCerificate( _
    ByVal sender As Object, _
    ByVal e As ServerCertificateValidateEventArgs)

    Const ignoredErrors As SslPolicyErrors = _
        SslPolicyErrors.RemoteCertificateChainErrors Or _
        SslPolicyErrors.RemoteCertificateNameMismatch

    If (e.SslPolicyErrors And Not ignoredErrors) = SslPolicyErrors.None Then
        e.IsValid = True
        Return
    End If
    e.IsValid = False
End Sub

AddHandler client.ServerCertificateValidate, AddressOf Validate

Tags: , , , , ,

One Response to “The handshake failed due to an unexpected packet format”

  1. Akula_V Says:

    Thanks for posting this.. helped me to find the actual cause.

    > Use Port 110 for regular Connection.
    > Use Port 995 for SSL Connection.

Leave a Reply