IMAP component for .NET

Mail.dll email component includes an excellent IMAP email component. Unleash the full potential of email management with Mail.dll’s outstanding IMAP email component.

It offers .NET developers an unparalleled tool for handling IMAP email protocol. From retrieving messages to managing folders and attachments, the IMAP component in Mail.dll simplifies complex tasks into user-friendly functions.

Mail.dll is available for all regular .NET framework versions as well as for most recent .net 6, 7 and .net 8 and higher.

IMAP, short for Internet Message Access Protocol, is one of the two most prevalent Internet standard protocols for e-mail retrieval, the other being Post Office Protocol – POP3 (also available in Mail.dll).

IMAP has many advantages over POP3, most important are using folders to group emails, saving seen/unseen state of the messages and search capability.

This article is going to show how easy is to connect to use IMAP client from .NET, download and parse unseen messages.

Installation

The easiest way to install Mail.dll is to download it from nuget via Package Manager:

PM> Install-Package Mail.dll

Alternatively you can download Mail.dll directly from our website.

Connect to IMAP

First you need connect to IMAP server. You should use Imap class for that. Using block ensures that IMAP connection is properly closed and disposed when you’re done.

using(Imap imap = new Imap())

In most cases you should be using TLS secured connection – ConnectSSL method will choose a correct port and perform SSL/TLS negotiation, then you perform IMAP authentictation:

	imap.ConnectSSL("imap.server.com");
	imap.UseBestLogin("user", "password");

Mail.dll supports OAuth 2.0 for authentication, you can find OAuth2 samples for Office365 and Gmail on the Mail.dll samples page.

For Gmail you may want to use Gmail’s App Passwords.

Search for unseen emails

As IMAP groups messages into folder you need to select a well know INBOX folder. All new, received emails are first placed in the INBOX folder first:

imap.SelectInbox();

Then you perform a search that find all unseen messages

List<long> uids = imap.Search(Flag.Unseen);

Download and parse emails

Finally you download emails one-by-one and parse them. You should use MailBuider class to parse emails:

var eml = imap.GetMessageByUID(uid);
IMail email = new MailBuilder().CreateFromEml(eml);

Entire code to download emails in .net

Entire code to download emails using IMAP is less than 20 lines:

using(Imap imap = new Imap())
{
	imap.ConnectSSL("imap.server.com");	// or Connect for no TLS
	imap.UseBestLogin("user", "password");

	imap.SelectInbox();
	List<long> uids = imap.Search(Flag.Unseen);

	foreach (long uid in uids)
	{
		var eml = imap.GetMessageByUID(uid);
		IMail email = new MailBuilder().CreateFromEml(eml);

		string subject = mail.Subject;
	}
	imap.Close();
}

and for those who like VB.NET more:

Using imap As New Imap()
	imap.ConnectSSL("imap.server.com")
	imap.UseBestLogin("user", "password")

	imap.SelectInbox()
	Dim uids As List(Of Long) = imap.Search(Flag.Unseen)

	For Each uid As Long In uids
		Dim mail As IMail = New MailBuilder()_
			.CreateFromEml(imap.GetMessageByUID(uid))

		Console.WriteLine(mail.Subject)
	Next
	imap.Close()
End Using

It can’t get much simpler than that!

Summary

You can use Mail.dll .NET IMAP component to:

It works perfectly with Exchange, Office365, Gmail and all other IMAP servers.

Just give Mail.dll a try and download it at: Mail.dll .NET IMAP component


Get Mail.dll

How to search IMAP in .NET

One of many advantages IMAP protocol has over POP3 protocol is the ability to search.

There are several ways of performing search using Mail.dll .NET IMAP library:

  • Search(Flag) – for common flag searches (seen, unseen, …).
  • SimpleImapQuery – easy one object query, where all conditions are joined with an AND operator.
  • Expression syntax – most advanced, allows using AND and OR operators and sorting.

IMAP search is done entirely on the server side, which means that it’s fast and doesn’t require Mail.dll client to download much data over the network.

Installation

The easiest way to install Mail.dll IMAP client for .NET is to download it from nuget via Package Manager:

PM> Install-Package Mail.dll

Alternatively you can download Mail.dll directly from our website.

Connect to IMAP

Let’s start with the basics: we’ll connect to the IMAP server in .NET app and authenticate:

// C# code:

using (Imap imap = new Imap())
{
    imap.ConnectSSL("imap.example.com");
    imap.UseBestLogin("user", "password");
    imap.SelectInbox();

    // Search code goes here

    imap.Close();
}
' VB.NET code:

Using imap As New Imap()
    imap.ConnectSSL("imap.example.com")
    imap.UseBestLogin("user", "password")
    imap.SelectInbox()

    ' Search code here

    imap.Close()
End Using

When using Gmail you can use application passwords, with Office 365 you’ll need to use OAuth 2.0 to authenticate.

Mail.dll fully supports OAuth 2.0 for authentication, you can find OAuth2 samples for Office365 and Gmail on the Mail.dll samples page.

Search(Flag)

Now, let’s look at the search code. The first and the simplest way to search is by using Imap.Search(Flag) method. This sample below finds all unseen email messages (those that have \UNSEEN flag).

// C#

List<long> uidList = imap.Search(Flag.Unseen);

// now download each message and get the subject
foreach (long uid in uidList)
{
    IMail message = new MailBuilder()
        .CreateFromEml(imap.GetMessageByUID(uid));

    string subject = message.Subject;
}
' VB.NET

Dim uidList As List(Of Long) = imap.Search(Flag.Unseen)

' now download each message and get the subject
For Each uid As Long In uidList
	Dim message As IMail = New MailBuilder()_
		.CreateFromEml(imap.GetMessageByUID(uid))

	Dim subject As String = message.Subject
Next

SimpleImapQuery

Second approach is to use an IMAP query object. The sample below searches for all unseen emails with a certain subject. All non-null SimpleImapQuery properties are combined using and operator.

// C#

SimpleImapQuery query = new SimpleImapQuery();
query.Subject = "subject to search";
query.Unseen = true;

List<long> uids = imap.Search(query);
' VB.NET

Dim query As New SimpleImapQuery()
query.Subject = "subject to search"
query.Unseen = True

Dim uids As List(Of Long) = imap.Search(query)

Expression syntax

Finally, the most advanced search option using Expression class. You can use AND, OR and NOT operators in your IMAP search.

Note that Mail.dll fully encapsulates IMAP search syntax, with easy to use and very readable .NET classes:

// C#

List<long> uids = imap.Search().Where(
    Expression.And(
        Expression.Not(Expression.Subject("subject not to search")),
        Expression.HasFlag(Flag.Unseen)));
' VB.NET

Dim uids As List(Of Long) = imap.Search().Where(_
    Expression.[And](_
        Expression.[Not](Expression.Subject("subject not to search")),_
        Expression.HasFlag(Flag.Unseen)))

Expression syntax with sorting

Expression search syntax also allows sorting (defined in RFC 5256).

This feature is not available for every IMAP server: you need to check if your IMAP server supports ImapExtension.Sort extension first.

// C#

List<long> uids = imap.Search()
    .Where(Expression.And(
            Expression.Not(Expression.Subject("subject not to search")),
            Expression.HasFlag(Flag.Unseen)))
    .Sort(SortBy.Multiple(
            SortBy.Date(),
            SortBy.Subject()));
' VB.NET

Dim uids As List(Of Long) = imap.Search() _
    .Where(Expression.[And]( _
        Expression.[Not](Expression.Subject("subject not to search")), _
        Expression.HasFlag(Flag.Unseen))) _
    .Sort(SortBy.Multiple( _
        SortBy.[Date](), _
        SortBy.Subject()))
)

Notice the neat trick in Mail.dll .NET client, that allows casting FluentSearch class, received from imap.Search() method, to List<longs>:

public static implicit operator List<long>(FluentSearch search)
{
        return search.GetList();
}

We tend to use it very often for builder objects used in our unit tests.

Suggested reading

If you like it just give it a try and download it at: Mail.dll .NET IMAP component


Get Mail.dll

Save all attachments to disk using IMAP

Unlock the potential of efficient email processing in .NET with this comprehensive guide on saving email attachments using Mail.dll’s IMAP component and IMAP protocol.

In this article, we’ll walk you through the step-by-step process of downloading email messages using Mail.dll’s IMAP component and, more importantly, demonstrate how to effortlessly save all attachments to your disk.

Email MIME structure

The first thing you need to know is that email attachments are tightly integrated with the email message itself, ensuring that they are conveniently stored and transport together.

In MIME (Multipurpose Internet Mail Extensions), email attachments are stored together with an email message to ensure a structured and standardized way of transmitting and receiving email content with multiple parts.

The primary reason for storing attachments within the email message is to maintain a single cohesive entity that encapsulates all the components of the email, including its text, formatting, and any attached files. By bundling attachments with the message, the entire email becomes a self-contained package, making it easier to handle and process by email clients and servers.

Attachments in Mail.dll

Invoking Imap.GetMessageByUID method is going to download entire email message, including all attachments.

Attachments are stored within the email as part of a mime tree. Usually Quoted-Printable or Base64 encoding is used.

However, with Mail.dll, you don’t need to worry about navigating this mime tree yourself. The library efficiently parses the email’s structure, effortlessly exposing all attachments as familiar .NET collections. This user-friendly approach simplifies the process of handling email attachments, allowing you to focus on building robust and efficient email management solutions with ease.

There are 4 collections that contain attachments:

  • IMail.Attachments – all attachments (includes Visuals, NonVisuals and Alternatives).
  • IMail.Visuals – visual elements, files that should be displayed to the user, such as images embedded in an HTML email.
  • IMail.NonVisuals – non visual elements, “real” attachments.
  • IMail.Alternatives – alternative content representations, for example ical appointment.

How to download all email attachments in .NET

To retrieve all attachments from an email, you can take advantage of the IMail.Attachments collection provided by Mail.dll. This collection serves as a comprehensive repository, housing all the attachments associated with the email.

Each attachment is represented by a dedicated MimeData object, which encapsulates the specific data and metadata of the attachment.

Using the IMail.Attachments collection eliminates the need for manual traversal of the email’s mime tree or deciphering complex structures. Instead, Mail.dll handles the heavy lifting for you, ensuring a streamlined and user-friendly experience when accessing email attachments programmatically.

Installation

The easiest way to install Mail.dll is to download it from nuget via Package Manager:

PM> Install-Package Mail.dll

Alternatively you can download Mail.dll directly from our website.

Download emails and all attachments

The C# code to download all emails and save all attachments using Mail.dll and IMAP is as follows.

using Limilabs.Client.IMAP;
using Limilabs.Mail;
using Limilabs.Mail.MIME
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        using(Imap imap = new Imap())
        {
            imap.ConnectSSL("imap.example.com");
            imap.UseBestLogin("user", "password");

            imap.SelectInbox();
            List<long>; uids = imap.Search(Flag.Unseen);
            foreach (long uid in uids)
            {
                var eml = imap.GetMessageByUID(uid);
                IMail email = new MailBuilder()
                    .CreateFromEml(eml);
                Console.WriteLine(email.Subject);

                foreach (MimeData mime in email.Attachments)
                {
                    mime.Save(@"c:\" + mime.SafeFileName);
                }
            }
            imap.Close();
        }
    }
};

Below is the VB.NET code for your reference:

Imports Limilabs.Client.IMAP
Imports Limilabs.Mail
Imports Limilabs.Mail.MIME
Imports System
Imports System.Collections.Generic

Public Module Module1
    Public Sub Main(ByVal args As String())

        Using imap As New Imap()
            imap.ConnectSSL("imap.example.com")
            imap.UseBestLogin("user", "password")

            imap.SelectInbox()
            Dim uids As List(Of Long) = imap.Search(Flag.Unseen)

            For Each uid As Long In uids
                Dim eml = imap.GetMessageByUID(uid)
                Dim email As IMail = New MailBuilder() _
                    .CreateFromEml(eml)
                Console.WriteLine(email.Subject)

                For Each mime As MimeData In email.Attachments
                    mime.Save("c:\" + mime.SafeFileName)
                Next
            Next
            imap.Close()
        End Using

    End Sub
End Module

Accessing attachment data

You can also save attachment to a specific stream using MimeData.Save(Stream stream).

You can get direct access to attachment binary data with MimeData.GetMemoryStream().

Finally you can get a byte array (byte[]) using MimeData.Data property.

Downloading only parts of the message

IMAP protocol provides very useful features in regard to working with attachments and all are available in Mail.dll .NET IMAP component.

With Mail.dll you can download only parts of email message, which in conjunction with getting basic email information without downloading entire message can make your code extremely fast.

Process emails embedded as attachments

In some situations you’ll receive a message that has another message attached.

You can use Mail.dll to extract all attachments from such inner messages no matter how deep the embedding level is.


Get Mail.dll

Authenticate using Gmail’s App Passwords to IMAP, POP3 and SMTP

An app password is a 16-digit passcode that serves as an alternative authentication method, granting Mail.dll .NET IMAP, POP3 or SMTP client access to your Gmail Account with the same level of security as using a regular password.

Your primary password can’t be used to authenticate anymore, because of Gmail’s secure access policies. Gmail introduced app passwords as a means to enhance account security.

This unique 16-digit passcode acts as a one-time key, eliminating the need to share your primary Google Account password with the application.

By generating an app password, users can rest assured that their sensitive credentials remain protected, and the Mail.dll .NET client can seamlessly interact with your Gmail Account, enabling efficient email management without compromising security.

OAuth 2.0 alternative

In many cases OAuth 2.0 is a better, but more complex option to access IMAP, POP3 and SMTP:

Enable 2-Step verification

Gmail’s App passwords can only be used with accounts that have 2-Step Verification turned on.

First go to your Google Account and on the left navigation panel, choose Security.

On the “Signing in to Google” panel:

  • Make sure I that 2-Step Verification is turned on
  • Finally choose App Passwords (you may need to scroll down a bit):

Generate new App password

On the “App password” screen select device and choose the device you’re using.

Then click Generate to create a new password:

New password will be generated – ready to use with Mail.dll clients.

Remember to copy the new password, because it won’t be displayed again:

Now you are ready to log in to your IMAP, SMTP, POP3 account using your email and the generated password (instead of your email’s primary password).

Authenticate using IMAP component

Mail.dll .NET email library provides a secure and efficient way to access email accounts, manage and parse email messages. It is a powerful .NET library that simplifies the implementation of IMAP functionality in various .NET applications.

We’ll use IMAP .NET client in an example below. Note that same password can be used for POP3 .NET client and SMTP .NET clients in exactly the same way.

Remember not to include any spaces when coping the app password to IMAP client’s authentication method, because authentication will fail.

C# code:

using (Imap client = new Imap()) 
{ 
    client.ConnectSSL("imap.gmail.com"); 
    client.UseBestLogin("XXXXX@gmail.com", "kvrcdzlicajaupje"); 

    // ... 

    client.Close(); 
}

VB.NET code:

Using imap As New Imap 
    imap.ConnectSSL("imap.gmail.com") 
    imap.UseBestLogin("XXXXX@gmail.com", "kvrcdzlicajaupje") 

    ' ... 

    imap.Close() 
End Using

Suggested reading


Get Mail.dll

Office 365: Basic Auth is disabled


Since October 2022 Basic Auth is by default disabled for IMAP and POP3 in Exchange Online / Office 365. Microsoft recommends using OAuth 2.0. This is not a big problem for Mail.dll email client for .net users as it support OAuth 2.0 in full.

Auth 2.0

You should switch to OAuth 2.0 for authentication purposes:

Daemons/Services: Password grant (MFA/2FA must be turned off for this account):
https://www.limilabs.com/blog/oauth2-password-grant-office365-exchange-imap-pop3-smtp

Daemons/Services: Client credential flow:
https://www.limilabs.com/blog/oauth2-client-credential-flow-office365-exchange-imap-pop3-smtp

Web apps (requires user interaction):
https://www.limilabs.com/blog/oauth2-web-flow-office365-exchange-imap-pop3-smtp

Standalone devices (requires very little interaction):
https://www.limilabs.com/blog/oauth2-device-flow-office365-exchange-imap-pop3-smtp

Desktop apps (requires user interaction):
https://www.limilabs.com/blog/oauth2-office365-exchange-imap-pop3-smtp

Re-enable Basic Auth

For some time it was possible to re-enable Basic Auth for IMAP and POP3 for your tenant – it is no longer possible to do that.