Search code examples
c#imapmailkit

MailKit search IMAP email came after specific UID


I am using MailKit .net library to fetch emails from gmail.

According to Getting only new mail from an IMAP server and IMAP: Search for messages with UID greater than X (or generally, after my last search)

I want to search all emails came after last remembered UID. lets say the last message fetched had a unique id of "123456". I want to search

123456:*

How do I achieve this search in MailKit?


Solution

  • There are multiple overloads of the Search method on an ImapFolder in MailKit. You'll want to use one of the overloads that take a IList<UniqueId> argument.

    Given that, now you'll need to create the list of UIDs to search on. I would recommend taking a look at the UniqueIdRange class in the MailKit namespace.

    If the last UID that your client program has seen in a previous session was 123456, you'll actually want your search to start with UID 123457. In IMAP-speak, * is just a wildcard for the "maximum unique id value in the folder". In MailKit, you can just use UniqueId.MaxValue.

    var range = new UniqueIdRange (new UniqueId ((uint) 123457), UniqueId.MaxValue);
    

    Now that you have the range 123457:*, you can perform the search:

    foreach (var uid in folder.Search (range, query)) {
        var message = folder.GetMessage (uid);
    }