Use TLS 1.3 for IMAP and SMTP connections

To take advantage of the most secure TLS 1.3 connections in e-mail .NET applications, you don’t necessarily need the latest .NET Core 3.0 or .NET 5 (even though the corresponding enum values are not defined in earlier versions).

The below shows how you can establish an IMAP connection using TLS 1.3. As an example, we’ll use GMail as the mail server and MailBee.NET Objects email component as the client. The key is setting ServicePointManager.SecurityProtocol static property prior to connecting to a mail server (be it IMAP, SMTP or POP3):

ServicePointManager.SecurityProtocol=SecurityProtocolType.Tls12 | (SecurityProtocolType)12288;

By default, MailBee.NET checks the value of ServicePointManager.SecurityProtocol, and if it’s set to non-default value, MailBee.NET will use all the flags listed in it as the allowed security protocols. In particular, SecurityProtocolType.Tls12 | (SecurityProtocolType)12288 means a combination of TLS 1.2 and TLS 1.3 (the best will be selected during the connection procedure, depending on what the mail server supports). .NET Framework may not have the corresponding value for TLS 1.3 in SecurityProtocolType enum yet so we use its int value which we cast to SecurityProtocolType type.

Here’s the complete sample with TLS 1.3 over Gmail’s IMAP:

using System;
using System.Net;
using System.Net.Security;
using MailBee;
using MailBee.ImapMail;

namespace ConsoleApplicationNet45
	class Program
		static void Main(string[] args)
			MailBee.Global.LicenseKey = "your key";
			Imap imp = new Imap();
			imp.Log.Enabled = true;
			imp.Log.Filename = @"C:\Temp\log.txt";
			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 |(SecurityProtocolType)12288; // Request TLS 1.3 but allow TLS 1.2 fallback
			imp.Connect("", 993);
			SslStream s = (SslStream)imp.GetStream();
			Console.WriteLine(s.SslProtocol.ToString()); // See that it's actually TLS 1.3
			imp.Login("", "password");

In my tests, the technique above works with .NET 4.5 and newer and .NET Core 2.1 and newer. TLS 1.3 support must also be installed and activated in Windows.

Use TLS 1.3 for IMAP and SMTP connections

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s