Mailkit SMTP - StartTLS and TLS flags

I am trying to connect to iCloud via SmtpClient

The settings I use are as follows:

Server Name: smtp.mail.me.com
SSL Required: Yes If you see an error message when using SSL, try using TLS or STARTTLS instead.
Port: 587
SMTP authentication required: Yes - with the appropriate username and password

If I use SSL, I get the message "Handshake failed due to unexpected packet format"

If I do not use the SSL visual studio debugger, it hangs when I connect.

I think the problem is that I am not telling SmtpClient to use tls, but I cannot find documentation on how to do this.

The code is as follows:

using (var client = new SmtpClient()) { client.Timeout = 1000 * 20; //client.Capabilities. client.AuthenticationMechanisms.Remove ("XOAUTH2"); client.Connect("SMTP.mail.me.com", 587, false); //dies here //client.Connect(servername, port, useSsl); //can I set tls or starttls here?? client.Authenticate(username, password); client.Send(FormatOptions.Default, message); } 

Is it possible to install TLS or StartTLS manually. One thing I tried is the following, but it doesn't seem to work.

 client.Connect(new Uri("smtp://" + servername + ":" + port + "/?starttls=true")); 

Thanks for any help with this.

+7
source share
3 answers

The Connect() method used allows you to enable / disable connected SSL connections, which is not the same as StartTLS.

Due to the confusion, I applied a separate Connect() method, which makes this more obvious what is happening:

 using (var client = new SmtpClient()) { // Note: don't set a timeout unless you REALLY know what you are doing. //client.Timeout = 1000 * 20; // Removing this here won't do anything because the AuthenticationMechanisms // do not get populated until the client connects to the server. //client.AuthenticationMechanisms.Remove ("XOAUTH2"); client.Connect ("smtp.mail.me.com", 587, SecureSocketOptions.StartTls); client.AuthenticationMechanisms.Remove ("XOAUTH2"); client.Authenticate (username, password); client.Send (message); } 

Try it.

+13
source

You can configure your settings on "SecureSocketOptions.Auto" something like this

 await client.ConnectAsync(mailService.Host, mailService.Port, SecureSocketOptions.Auto); 

MailKit will automatically decide to use SSL or TLS.

0
source

According to MailKit Doc

 Connect(string host,int port,bool useSsl,CancellationToken cancellationToken = null) 

The useSsl argument only controls whether the client establishes an SSL connection. In other words, even if the useSsl parameter is false, SSL / TLS can still be used if the mail server supports the STARTTLS extension.

0
source

All Articles