14

I have a problem sending email via Office 365 SMTP and MailKit. The exception I get is:

Unhandled Exception: System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

https://github.com/jstedfast/MailKit

Code:

var smtpClient = new SmtpClient();

smtpClient.Connect("smtp.office365.com", 587, true);

Microsoft Office 365 settings should be correct:

https://support.office.com/en-us/article/POP-and-IMAP-settings-for-Outlook-Office-365-for-business-7fc677eb-2491-4cbc-8153-8e7113525f6c

The weird thing is that if I use the following everything works, even though Office 365 says SSL is required.

smtpClient.Connect("smtp.office365.com", 587, false);
Ogglas
  • 62,132
  • 37
  • 328
  • 418

1 Answers1

26

Got another error after posting this question which led me to the answer:

Handshake failed due to an unexpected packet format

The solution is to connect to Office 365 like this instead:

smtpClient.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls);
Ogglas
  • 62,132
  • 37
  • 328
  • 418
  • 3
    Just commenting to confirm that this is the correct solution. SMTP really only uses SSL-wrapped connections on port 465. Port 2 and 587 use StartTLS if they use "SSL" at all. This is, unfortunately, not generally explained well in configuration guides. – jstedfast Jan 26 '17 at 23:46
  • This just saved me too. I made the mistake of reading the documentation :) – Martin Horton Aug 08 '17 at 21:59
  • This solution does not work for me after deploying to Ubuntu server. Any ideas? – Ajit Singh Oct 28 '21 at 15:27