Search code examples
c#query-stringexchangewebservices

C# Get mails AFTER a specified date using Microsoft.Exchange.WebSercvices EWS


I'm using the EWS to download mails. As the mailbox is quite large, I'd like to filter the mails with the querystring. I found a method to only download mails of a specified date using Received:20/11/2019 but

  1. This is not returning all the mails from this date (why - it seems, that only unread mails with attachments are part of the results)
  2. I'd like to get all mails from 20 Nov. 2019 and later

Here is my code:

    Microsoft.Exchange.WebServices.Data.ExchangeService exchange = new Microsoft.Exchange.WebServices.Data.ExchangeService(Microsoft.Exchange.WebServices.Data.ExchangeVersion.Exchange2013);
    exchange.Credentials = new Microsoft.Exchange.WebServices.Data.WebCredentials("User", "********", "Domain");
    exchange.AutodiscoverUrl("Name@domain.com");
    string QString = "Recieved:20/11/2019";

    if (exchange != null)
    {
        Microsoft.Exchange.WebServices.Data.FindItemsResults<Microsoft.Exchange.WebServices.Data.Item> Results = exchange.FindItems(Microsoft.Exchange.WebServices.Data.WellKnownFolderName.Inbox, QString, new Microsoft.Exchange.WebServices.Data.ItemView(100));

        foreach(Microsoft.Exchange.WebServices.Data.Item MI in Results)
        {
            /*Print subject to command window*/
            System.Console.WriteLine(MI.Subject);
        }
    }

I found an answer here, but its PHP and I'm not really skilled in it: Getting emails after a specific date with php-ews (Exchange Web Services)


Solution

  • Ah, SearchFilter does work well for me:

    Microsoft.Exchange.WebServices.Data.SearchFilter SF = new Microsoft.Exchange.WebServices.Data.SearchFilter.IsGreaterThanOrEqualTo(Microsoft.Exchange.WebServices.Data.ItemSchema.DateTimeReceived, new System.DateTime(2019,11,20));
    Microsoft.Exchange.WebServices.Data.FindItemsResults<Microsoft.Exchange.WebServices.Data.Item> Results = exchange.FindItems(Microsoft.Exchange.WebServices.Data.WellKnownFolderName.Inbox, SF, new Microsoft.Exchange.WebServices.Data.ItemView(100));