Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of UIDs in reverse order with MailKit?

I would like to get the latest 100 UIDs from the inbox using MailKit. I am accessing a Gmail mailbox which does not appear to support the SORT extension so I am unable to use OrderBy.

Here is my code. The problem is that it appears to retrieve the oldest 100 emails rather the latest ones (which is how I would expect it to work). Is there a way to do this?

Option A - looks promising only gets the 100 oldest emails UIDs and I want the 100 newest:

            imap.Inbox.Open(FolderAccess.ReadOnly);
            var orderBy = new [] { OrderBy.ReverseArrival };
            var items = imap.Inbox.Fetch(0, limit, MessageSummaryItems.UniqueId);

Option B - gets all UIDs by date order (but does not work on Gmail anyway):

            imap.Inbox.Open(FolderAccess.ReadOnly);
            var orderBy = new [] { OrderBy.ReverseArrival };
            SearchQuery query = SearchQuery.All;
            var items = imap.Inbox.Search(query, orderBy);

The IMAP server does not support the SORT extension.

The reason is to quickly scan the mailbox in order to improve responsiveness to user.

like image 761
mike nelson Avatar asked Dec 05 '22 22:12

mike nelson


1 Answers

You were pretty close in Option A, you just used the wrong values for the first 2 arguments.

This is what you want:

imap.Inbox.Open (FolderAccess.ReadOnly);
if (imap.Inbox.Count > 0) {
    // fetch the UIDs of the newest 100 messages
    int index = Math.Max (imap.Inbox.Count - 100, 0);
    var items = imap.Inbox.Fetch (index, -1, MessageSummaryItems.UniqueId);
    ...
}

The way that IMailFolder.Fetch (int, int, MessageSummaryItems) works is that the first int argument is the first message index and the second argument is the last message index in the range (-1 is a special case that just means "the last message in the folder").

Since once we open the folder, we can use the IMailFolder.Count property to get the total number of messages in the folder, we can use that to count backwards from the end to get our starting index. We want the last 100, so we can do folder.Count - 100. We use Math.Max() to make sure we don't get a negative value if the number of messages in the folder is less than 100.

Hope that helps.

like image 63
jstedfast Avatar answered Dec 08 '22 12:12

jstedfast