How to search IMAP in .NET

Recently Mail.dll email component got new IMAP client.

I must say that I really enjoyed implementing IMAP search.

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

Let’s start with the basics: we’ll connect to the IMAP server and login:

// C# code:

using (Imap imap = new Imap())
{
    imap.Connect("server");
    imap.Login("user", "password");
    imap.SelectInbox();

    // Search code goes here

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

Using imap As New Imap()
    imap.Connect("server")
    imap.Login("user", "password")
    imap.SelectInbox()

    ' Search code here

    imap.Close(True)
End Using

Now the first and the simplest way using Imap.SearchFlag method:

// C# code:

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

// now download each message and display the subject
foreach (long uid in uidList)
{
    IMail message = new MailBuilder()
        .CreateFromEml(imap.GetMessageByUID(uid));
    Console.WriteLine(message.Subject);
}
' VB.NET code:

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

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

Second approach is to use the IMAP query object.
We will search all unseen emails with certain subject:

// C# code:

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

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

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

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

Finally most advanced search option using Expression class.
You can use And, Or and Not operators in your IMAP search:

// C# code:

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

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

Notice the neat trick in Mail.dll that allows casting FluentSearch class
received from imap.Search(…) to List

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

I tend to use it very often for builder objects used in unit testing.

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

Tags: ,

3 Responses to “How to search IMAP in .NET”

  1. Gene Says:

    Can you search by message id? I see you have a header option to search by but not sure how to use it.

  2. Pawel Lesnikowski Says:

    Yes, you can search by message-id header:

    List<long> uids =  imap.Search(
         Expression.Header("Message-ID", "<message@id.com>"));
    
  3. Gene Says:

    Worked perfect!!

Leave a Reply