Search Emails in C# and VB.NET

One of the advanced IMAP features is a search command, which is supported by all IMAP servers regardless of their protocol version. With this, you can find messages that match certain criteria.

To search for specific emails with GemBox.Email, you can use the ImapClient.SearchMessageNumbers or ImapClient.SearchMessageUids methods. Since search queries can be quite complex, GemBox.Email allows developers to construct custom queries according to RFC 3501, Section 6.4.4.

The following example shows how to search for messages that match various criteria.

Screenshot of searching messages with ImapClient
Search messages with IMAP client in C# and VB.NET
using System;
using System.Collections.Generic;
using GemBox.Email;
using GemBox.Email.Imap;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        using (ImapClient imap = new ImapClient("<ADDRESS> (e.g. imap.gmail.com)"))
        {
            imap.Connect();
            imap.Authenticate("<USERNAME>", "<PASSWORD>");
            imap.SelectInbox();

            // Search for messages whose subject contains 'Example' text.
            IList<int> messages = imap.SearchMessageNumbers("SUBJECT Example");
            Console.WriteLine($"Number of messages with 'Example' in subject: {messages.Count}");

            // Search for 'unseen' messages sent by 'sender@example.com'.
            messages = imap.SearchMessageNumbers("UNSEEN FROM sender@example.com");
            Console.WriteLine($"Number of 'unseen' messages sent by 'sender@example.com': {messages.Count}" );
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports GemBox.Email
Imports GemBox.Email.Imap

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Using imap As New ImapClient("<ADDRESS> (e.g. imap.gmail.com)")

            imap.Connect()
            imap.Authenticate("<USERNAME>", "<PASSWORD>")
            imap.SelectInbox()

            ' Search for messages whose subject contains 'Example' text.
            Dim messages As IList(Of Integer) = imap.SearchMessageNumbers("SUBJECT Example")
            Console.WriteLine($"Number of messages with 'Example' in subject: {messages.Count}")

            ' Search for 'unseen' messages sent by 'sender@example.com'.
            messages = imap.SearchMessageNumbers("UNSEEN FROM sender@example.com")
            Console.WriteLine($"Number of 'unseen' messages sent by 'sender@example.com': {messages.Count}")
        End Using
    End Sub
End Module

For more information about ImapClient, check out our IMAP Client Connection example.

Check next example or download examples from GitHub.