Search filters not working when using AND operator on EWS?

Jane Doris 1 Reputation point
2020-07-08T13:41:09.117+00:00

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@keyman .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!

Not Monitored
Not Monitored
Tag not monitored by Microsoft.
42,915 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Vahid Ghafarpour 22,620 Reputation points
    2023-09-18T18:15:33.91+00:00

    When you use the LogicalOperator.And to combine multiple search filters, you are asking for items that satisfy all of the specified conditions simultaneously. In your case, you want to filter emails that are both sent today (DateTimeReceived falls within today's date range) and from a specific sender. It's possible that there are no emails that meet both criteria, which is why you're not getting any results.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.