Search code examples
c#exchangewebservices

Search filters not working when using AND operator on EWS?


I am trying to filter through emails using two filters: emails sent TODAY and emails from a specific recipient. I tried the following approach:

DateTime searchdate = DateTime.Today;
            SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, searchdate);
            SearchFilter lessthanfilter = new SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, searchdate.AddHours(24));
            SearchFilter senderFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.From, "some-email-here@domain.com");
            SearchFilter dateFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, greaterthanfilter, lessthanfilter);
            SearchFilter allFilters = new SearchFilter.SearchFilterCollection(LogicalOperator.And, dateFilter, senderFilter);
            Folder folder = Folder.Bind(service, WellKnownFolderName.Inbox);
            FindItemsResults<Item> results = folder.FindItems(allFilters, new ItemView(50));
            foreach(Item i in results)
            {
                Console.WriteLine(i.Subject);
            }

If I use the filters separately, everything works fine. I either get the emails filtered by the sender or the emails filtered by the received date. If I change the LogicalOperator to OR, everythings works great as well. For some reason, when I add the LogicalOperator.And, no emails are returned.

If you know a better way, please let me know!


Solution

  • As per @glen-scales advised, I went and looked at query strings which at first, did not help me out because they weren't solving the issue either! Turns out it was a problem of how you write the query string! This worked perfectly for me:

    FindItemsResults<Item> findResults = service.FindItems(folder.Id, "from:email@domain.com AND Received:Today", new ItemView(20));
    

    Whereas this did not work at all:

    FindItemsResults<Item> findResults = service.FindItems(folder.Id, "(from:email@domain.com) AND (Received:Today)", new ItemView(20));
    

    If you did not notice, the difference is the use of the parentheses (although they should not be problematic, I believe).

    For further documentation on query strings, refer to the following link : https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/ee693615%28v%3dexchg.140%29