How to use the folder.Search() method?

Jan 4, 2016 at 8:42 PM
Can you give us some examples of how to use the Search() method to get a filtered list of messages?

I'm mostly interested in pulling down messages by a date range, like
  • ReceivedDate => 2015-01-01 and ReceivedDate <= 2015-01-31
or by a string match on the subject:
  • subject.Contains("Blah")
or on the from field:
Is this kind of filtering possible?
Jan 8, 2016 at 1:09 PM
It looks like ImapX's Search() method takes a query string that you have to provide yourself, which means you'll have to do a bit of reading up on the IMAP SEARCH syntax:

https://tools.ietf.org/html/rfc3501#page-49

There are IMAP extensions that provide more SEARCH options as well.

For MailKit, I ended up implementing a SearchQuery class that helps construct these queries without needing to know the IMAP SEARCH syntax. Maybe something like that could be added to ImapX.

To use your first set of search criteria as an example:
// let's search for all messages received between 2015-01-01 and 2015-01-31
var query = SearchQuery.DeliveredAfter (DateTime.Parse ("2015-01-01"))
    .And (SearchQuery.DeliveredBefore (DateTime.Parse ("2015-01-31")));

foreach (var uid in inbox.Search (query)) {
    var message = inbox.GetMessage (uid);
    Console.WriteLine ("[match] {0}: {1}", uid, message.Subject);
}
You can even sort them:
// let's do the same search, but this time sort them in reverse arrival order
var orderBy = new [] { OrderBy.ReverseArrival };
foreach (var uid in inbox.Search (query, orderBy)) {
    var message = inbox.GetMessage (uid);
    Console.WriteLine ("[match] {0}: {1}", uid, message.Subject);
}

// you'll notice that the orderBy argument is an array... this is because you
// can actually sort the search results based on multiple columns:
orderBy = new [] { OrderBy.ReverseArrival, OrderBy.Subject };
foreach (var uid in inbox.Search (query, orderBy)) {
    var message = inbox.GetMessage (uid);
    Console.WriteLine ("[match] {0}: {1}", uid, message.Subject);
}
Hopefully this gives Pavel some good ideas :)
Jan 8, 2016 at 1:32 PM
This is how you'd make the the particular queries you asked for in ImapX:
folder.Search ("AND SINCE \"1-Jan-2015\" BEFORE \"31-Jan-2015\"");
folder.Search ("SUBJECT \"Blah\"");
folder.Search ("FROM \"BillBob@gmail.com\"");
The DateTime.ToString() format you want to use for the dates is "d-MMM-yyyy", since I'm sure you'll want that info.

Hope that helps.