I want to integrate a few mail capabilities into a project and looking for some libraries to do the trick I found MailKit by Jeffrey Stedfast which is terrific.

Went to create the API/Middleware for my project, and when I connected to Zoho Mail, Google and Microsoft, everything working as expected with a custom implementation of the method I did for fetching the results.

int lowerIndex = inbox.Count - (Page == 0 ? Quantity : Page * Quantity);
int upperIndex = lowerIndex + Quantity;
 var records = await inbox.FetchAsync(lowerIndex, upperIndex, theHeaders);

I did the calculation of the lower index and upper index (this is the pagination, we are not going to get 1069 from one shot). The tricky part of this, is all the service mentioned above gives proper index, like the exact first record/endrecord but… then, tried to do the same, with a custom mail hosted, in Zimbra in this case, should work right? But no! It gives one number above the requested. i.e If I have 50 emails in a folder and I request the 10 latest emails according to the formula it is lowerIndex = 40, upperIndex =50, for some odd reason, Zimbra returns lowerIndex = 41, upperIndex=51 which is outside of the array and will give an error.

So after a while dealing with this and searching for solutions I found this on Stack Overflow. The solution that Vladimir propose make sense to me so. I get the ID of the sorted list and limit by a Skip and Take function:

 var ids = (await inbox.SortAsync(SearchOptions.All, SearchQuery.All, new[] { OrderBy.ReverseDate }).ConfigureAwait(true)).UniqueIds
                        .Skip(Page*Quantity)
                        .Take(Quantity)
                        .ToArray();
var item = await inbox.FetchAsync(ids, theHeaders);

After this, fetching was happening, now it’s time to see if this is the best approach performing wise but for now it does the trick 🙂