- Are MimeKit and MailKit completely free? Can I use them in my proprietary product(s)?
- Why do I get
"MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection."when I try to Connect? - How can I get a protocol log for IMAP, POP3, or SMTP to see what is going wrong?
- Why doesn't MailKit find some of my GMail POP3 or IMAP messages?
- How can I access GMail using MailKit?
- How can I log in to a GMail account using OAuth 2.0?
- How can I create a message with attachments?
- How can I get the main body of a message?
- How can I tell if a message has attachments?
- Why doesn't the
MimeMessageclass implementISerializableso that I can serialize a message to disk and read it back later? - How can I parse messages?
- How can I save messages?
- How can I save attachments?
- How can I get the email addresses in the From, To, and Cc headers?
- Why do attachments with unicode filenames appear as "ATT0####.dat" in Outlook?
- How can I decrypt PGP messages that are embedded in the main message text?
- How can I reply to a message?
- How can I forward a message?
- How can I get the number of unread messages in a folder?
- How can I search for messages delivered between two dates?
- What does "The ImapClient is currently busy processing a command." mean?
- Why do I get InvalidOperationException: "The folder is not currently open."?
- Why doesn't ImapFolder.MoveTo() move the message out of the source folder?
- How can I mark messages as read using IMAP?
- How can I re-synchronize the cache for an IMAP folder?
- How can I send email to the SpecifiedPickupDirectory?
- How can I request a notification when the message is read by the user?
- How can I process a read receipt notification?
Yes. MimeKit and MailKit are both completely free and open source. They are both covered under the MIT license.
Q: Why do I get "MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection." when I try to Connect?
When you get an exception with that error message, it usually means that you are encountering one of the following scenarios:
There are 2 different ways to use SSL/TLS encryption with mail servers.
The first way is to enable SSL/TLS encryption immediately upon connecting to the SMTP, POP3 or IMAP server. This method requires an "SSL port" because the standard port defined for the protocol is meant for plain-text communication.
The second way is via a STARTTLS command (aka STLS for POP3) that is optionally
supported by the server.
Below is a table of the protocols supported by MailKit and the standard plain-text ports
(which either do not support any SSL/TLS encryption at all or only via the STARTTLS
command extension) and the SSL ports which require SSL/TLS encryption immediately upon a
successful connection to the remote host.
| Protocol | Standard Port | SSL Port |
|---|---|---|
| SMTP | 25 or 587 | 465 |
| POP3 | 110 | 995 |
| IMAP | 143 | 993 |
It is important to use the correct SecureSocketOptions for the port that you are connecting to.
If you are connecting to one of the standard ports above, you will need to use SecureSocketOptions.None,
SecureSocketOptions.StartTls or SecureSocketOptions.StartTlsWhenAvailable.
If you are connecting to one of the SSL ports, you will need to use SecureSocketOptions.SslOnConnect.
You could also try using SecureSocketOptions.Auto which works by choosing the appropriate option to use
by comparing the specified port to the ports in the above table.
2. The mail server that you are connecting to is using an expired (or otherwise untrusted) SSL certificate.
Often times, mail servers will use self-signed certificates instead of using a certificate that has been signed by a trusted Certificate Authority. Another potential pitfall is when locally installed anti-virus software replaces the certificate in order to scan web traffic for viruses.
When your system is unable to validate the mail server's certificate because it is not signed by a known and trusted Certificate Authority, the above error will occur.
You can work around this problem by supplying a custom RemoteCertificateValidationCallback and setting it on the client's ServerCertificateValidationCallback property.
In the simplest example, you could do something like this (although I would strongly recommend against it in production use):
using (var client = new SmtpClient ()) {
client.ServerCertificateValidationCallback = (s,c,h,e) => true;
client.Connect (hostName, port, SecureSocketOptions.Auto);
// ...
}A better solution might be to compare the certificate's common name, issuer, serial number, and fingerprint to known values to make sure that the certificate can be trusted. Take the following code snippet as an example of how to do this:
bool MyServerCertificateValidationCallback (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
// Note: The following code casts to an X509Certificate2 because it's easier to get the
// values for comparison, but it's possible to get them from an X509Certificate as well.
if (certificate is X509Certificate2 certificate2) {
var cn = certificate2.GetNameInfo (X509NameType.SimpleName, false);
var fingerprint = certificate2.Thumbprint;
var serial = certificate2.SerialNumber;
var issuer = certificate2.Issuer;
return cn == "imap.gmail.com" && issuer == "CN=GTS CA 1O1, O=Google Trust Services, C=US" &&
serial == "00A15434C2695FB1880300000000CBF786" &&
fingerprint == "F351BCB631771F19AF41DFF22EB0A0839092DA51";
}
return false;
}The downside of the above example is that it requires hard-coding known values for "trusted" mail server certificates which can quickly become unweildy to deal with if your program is meant to be used with a wide range of mail servers.
The best approach would be to prompt the user with a dialog explaining that the certificate is
not trusted for the reasons enumerated by the
SslPolicyErrors
argument as well as potentially the errors provided in the
X509Chain.
If the user wishes to accept the risks of trusting the certificate, your program could then return true.
For more details on writing a custom SSL certificate validation callback, it may be worth checking out the SslCertificateValidation.cs example.
3. A Certificate Authority CRL server for one or more of the certificates in the chain is temporarily unavailable.
Most Certificate Authorities are probably pretty good at keeping their CRL and/or OCSP servers up 24/7, but occasionally they do go down or are otherwise unreachable due to other network problems between you and the server. When this happens, it becomes impossible to check the revocation status of one or more of the certificates in the chain.
To ignore revocation checks, you can set the
CheckCertificateRevocation
property of the IMAP, POP3 or SMTP client to false before you connect:
using (var client = new SmtpClient ()) {
client.CheckCertificateRevocation = false;
client.Connect (hostName, port, SecureSocketOptions.Auto);
// ...
}4. The server does not support the same set of SSL/TLS protocols that the client is configured to use.
MailKit attempts to keep up with the latest security recommendations and so is continuously removing older SSL and TLS protocols that are no longer considered secure from the default configuration. This often means that MailKit's SMTP, POP3 and IMAP clients will fail to connect to servers that are still using older SSL and TLS protocols. Currently, the SSL and TLS protocols that are not supported by default are: SSL v2.0, SSL v3.0, TLS v1.0 and TLS v1.1.
You can override MailKit's default set of supported SSL and TLS protocols by setting the value of the SslProtocols property on your SMTP, POP3 or IMAP client.
For example:
using (var client = new SmtpClient ()) {
// Allow SSLv3.0 and all versions of TLS
client.SslProtocols = SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13;
client.Connect ("smtp.gmail.com", 465, true);
// ...
}All of MailKit's client implementations have a constructor that takes a nifty IProtocolLogger interface for logging client/server communications. Out of the box, you can use the handy ProtocolLogger class. Here are some examples of how to use it:
// log to a file called 'imap.log'
var client = new ImapClient (new ProtocolLogger ("imap.log"));// log to standard output (i.e. the console)
var client = new ImapClient (new ProtocolLogger (Console.OpenStandardOutput ()));Note: When submitting a protocol log as part of a bug report, make sure to scrub any sensitive
information including your authentication credentials. This information will generally be the base64
encoded blob immediately following an AUTHENTICATE or AUTH command (depending on the type of server).
The only exception to this case is if you are authenticating with NTLM in which case I may need this
information, but only if the bug/error is in the authentication step.
By default, GMail's POP3 and IMAP server does not behave like standard POP3 or IMAP servers and hides messages from clients using those protocols (as well as having other non-standard behavior).
If you want to configure your GMail POP3 or IMAP settings to behave the way POP3 and IMAP are
intended to behave according to their protocol specifications, you'll need to log in to your
GMail account via your web browser and navigate to the Forwarding and POP/IMAP tab of your
GMail Settings page and set your options to look like this:
The first thing that you will need to do is to configure your GMail account to enable less secure apps, or you'll need to use OAuth 2.0 authentication (which is a bit more complex).
Then, assuming that your GMail account is user@gmail.com, you would use the following
code snippet to connect to GMail via IMAP:
using (var client = new ImapClient ()) {
client.Connect ("imap.gmail.com", 993, SecureSocketOptions.SslOnConnect);
client.Authenticate ("user@gmail.com", "password");
// do stuff...
client.Disconnect (true);
}Connecting via POP3 or SMTP is identical except for the host names and ports (and, of course, you'd
use a Pop3Client or SmtpClient as appropriate).
The first thing you need to do is follow Google's instructions for obtaining OAuth 2.0 credentials for your application.
(Or, as an alternative set of step-by-step instructions, you can follow the directions that I have written in GMailOAuth2.md.)
Once you've done that, the easiest way to obtain an access token is to use Google's Google.Apis.Auth library:
const string GMailAccount = "username@gmail.com";
var clientSecrets = new ClientSecrets {
ClientId = "XXX.apps.googleusercontent.com",
ClientSecret = "XXX"
};
var 