Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MailKit C# SmtpClient.Connect() to Office 365 generating exception: "An existing connection was forcibly closed by the remote host"

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);
like image 817
Ogglas Avatar asked Jan 26 '17 11:01

Ogglas


People also ask

What is MailKit C#?

MailKit is an Open Source cross-platform . NET mail-client library that is based on MimeKit and optimized for mobile devices.

Is MimeKit free?

MimeKit and MailKit are open source and completely free for commercial use.

Why use MimeKit?

Thanks to MimeKit on that MailKit is built on, you can do everything imaginable with the email itself. The more complex your tasks with emails are, the better suited is MailKit. Nevertheless, when you just want to send an email you can do that with MailKit without much effort.

What is MimeKit C#?

MimeKit is a C# MIME creation and parser library with support for S/MIME, PGP, DKIM, TNEF, and Unix mbox spools.


1 Answers

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);
like image 89
Ogglas Avatar answered Sep 27 '22 22:09

Ogglas