Search Email Messages in C#, VB.NET

Spire.Email allows developers to search mailbox for email messages that match the given search criteria. This article illustrates how to search email messages using Spire.Email component.

Detail steps:

Step 1: Create an ImapClient instance.

ImapClient imap = new ImapClient();

Step 2: Set host, port, authentication and connection protocol.

imap.Host = "outlook.office365.com";
imap.Port = 143;
imap.Username = "LeonDavisLD@outlook.com";
imap.Password = "password";
imap.ConnectionProtocols = ConnectionProtocols.Ssl;

Step 3: connect the imap server.

imap.Connect();

Step 4: Select Inbox folder.

imap.Select("Inbox");

Step 5: Search email messages in the folder that match the search criteria.

//Search email messages sent from “Alice”
ImapMessageCollection messages = imap.Search("'From' Contains 'Alice'");
Console.WriteLine("Number of messages sent from Alice: " + messages.Count);

//Search email messages with “Spire” string in subject
messages = imap.Search("'Subject' Contains 'Spire'");
Console.WriteLine("Number of messages with 'Spire' in subject: " + messages.Count);

Screenshot:

Search Email Messages in C#, VB.NET

Full code:

[C#]
//Create an ImapClient instance
ImapClient imap = new ImapClient();

//Set host, port, authentication and connection protocol
imap.Host = "outlook.office365.com";
imap.Port = 143;
imap.Username = "LeonDavisLD@outlook.com";
imap.Password = "password";
imap.ConnectionProtocols = ConnectionProtocols.Ssl;

//Connect the imap server
imap.Connect();

//Select Inbox folder
imap.Select("Inbox");

//Search email messages sent from "Alice"
ImapMessageCollection messages = imap.Search("'From' Contains 'Alice'");
Console.WriteLine("Number of messages sent from Alice: " + messages.Count);

//Search email messages with “Spire” string in subject
messages = imap.Search("'Subject' Contains 'Spire'");
Console.WriteLine("Number of messages with 'Spire' in subject: " + messages.Count);
[VB.NET]
'Create an ImapClient instance
Dim imap As New ImapClient()

'Set host, port, authentication and connection protocol
imap.Host = "outlook.office365.com"
imap.Port = 143
imap.Username = "LeonDavisLD@outlook.com"
imap.Password = "password"
imap.ConnectionProtocols = ConnectionProtocols.Ssl

'Connect the imap server
imap.Connect()

'Select Inbox folder
imap.[Select]("Inbox")

'Search email messages sent from "Alice"
Dim messages As ImapMessageCollection = imap.Search("'From' Contains 'Alice'")
Console.WriteLine("Number of messages sent from Alice: " + messages.Count)

'Search email messages with “Spire” string in subject
messages = imap.Search("'Subject' Contains 'Spire'")
Console.WriteLine("Number of messages with 'Spire' in subject: " + messages.Count)