11
votes

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);
1

1 Answers

23
votes

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);