Filter Messages From Exchange Mailbox

The IEWSClient class provides the ListMessages() method which gets all messages from a mailbox. To get only messages which match some condition, use the overloaded ListMessages() method which takes the MailQuery class as an argument. The MailQuery class provides various properties for specifying conditions, for example, date, subject, sender, and recipient.

Filtering Messages

To get filtered messages from a mailbox:

  1. Connect to the Exchange server.
  2. Create an instance of MailQuery and set the desired properties.
  3. Call the IEWSClient->ListMessages method and pass the MailQuery in the parameters to get the filtered messages only.

The following code snippet shows you how to get messages that have the string “Newsletter” in the subject and were sent today.

Filter Messages on Criteria

The code samples above filters messages based on the email subject and date. We can filter on other properties too. Below are some examples of setting the conditions using MailQuery.

Filter Criteria Today’s Date

The following code snippet shows you how to filter emails on the basis of today’s date.

Filter Criteria Date Range

The following code snippet shows you how to filter emails on the basis of a date range.

Filter Criteria Specific Sender

The following code snippet shows you how to filter emails on the basis of a specific sender.

Filter Criteria Specific Domain

The following code snippet shows you how to filter emails on the basis of a specific domain.

Filter Criteria Specific Recipient

The following code snippet shows you how to filter emails on the basis of a specific recipient.

Filter Criteria By MessageID

The following code snippet shows you how to filter emails on the basis of MessageID.

Filter Criteria All Mail Delivery Notifications

The following code snippet shows you how to filter emails on the basis of all mail delivery notifications.

Filter by Message Size

Building Complex Queries

If different MailQueryBuilder properties are set in a separate statement, all the conditions are matched. For example, to get a message in a particular date range and from a specific host, write three statements:

Combining Queries with AND

The following code snippet shows you how to Combine Queries with AND.

Combining Queries with OR

MailQueryBuilder provides the Or() method which takes two MailQuery instances as parameters. It gets messages that match any of the two conditions specified. The example below filters messages that either has the word “test” in the subject or “noreply@host.com” as the sender. The following code snippet shows you how to combine queries with OR.

Case-Sensitive Email Filtering

Emails can be filtered based on case-sensitivity by specifying the IgnoreCase flag in the filter criteria as shown in the following code snippet.

Filtering Messages with Paging Support