16

I am trying to use MailKit to send an email message via "smtp.office365.com". Here is the code I'm using.

using (var client = new SmtpClient(new ProtocolLogger("smtp.log")))
{
    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
    client.Connect("smtp.office365.com", 587, SecureSocketOptions.SslOnConnect);
    client.Authenticate(new SaslMechanismNtlmIntegrated());
    Debug.WriteLine(client.IsAuthenticated);
    client.Send(message);
    client.Disconnect(true);
}

The SaslMechanismNtlmIntegrated class I got from this comment on GitHub.

Whenever I run this code, I get an SslHandshakeException.

Here are the details of the exception:

MailKit.Security.SslHandshakeException
  HResult=0x80131500
  Message=An error occurred while attempting to establish an SSL or TLS connection.

One possibility is that you are trying to connect to a port which does not support SSL/TLS.

The other possibility is that the SSL certificate presented by the server is not trusted by the system for one or more of the following reasons:
1. The server is using a self-signed certificate which cannot be verified.
2. The local system is missing a Root or Intermediate certificate needed to verify the server's certificate.
3. The certificate presented by the server is expired or invalid.

See https://github.com/jstedfast/MailKit/blob/master/FAQ.md#InvalidSslCertificate for possible solutions.
  Source=MailKit
  StackTrace:
   at MailKit.Net.Smtp.SmtpClient.<ConnectAsync>d__70.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MailKit.Net.Smtp.SmtpClient.Connect(String host, Int32 port, SecureSocketOptions options, CancellationToken cancellationToken)
   at QuoteAndOrder.SpecialsQuoteWindow.BtnEmail_Click(Object sender, RoutedEventArgs e) in SpecialsQuoteWindow.xaml.cs:line 501

Inner Exception 1:
IOException: The handshake failed due to an unexpected packet format.

I went to the FAQ mentioned in the details, but the workaround given did not resolve the issue.

Dave F
  • 821
  • 1
  • 9
  • 20
  • 5
    Try using `SecureSocketOptions.StartTls` instead of `SecureSocketOptions.SslOnConnect` – willaien Mar 21 '19 at 19:18
  • I've updated the FAQ to explain the different types of SSL connections since people keep getting confused about what options to use and when. – jstedfast Mar 22 '19 at 00:01
  • For anyone else out there getting this exception when using a legacy app targeting .NET Core 2.0, you can fix the problem by running the app on .NET Core 2.2.0 or later (e.g. by running `dotnet --fx-version 2.2.0 .\YourAppNameHere.dll`). – Eric Mutta Oct 01 '21 at 14:17

1 Answers1

22

The solution mentioned by willaien resolved this issue. Namely, using SecureSocketOptions.StartTls instead of SecureSocketOptions.SslOnConnect.

Dave F
  • 821
  • 1
  • 9
  • 20