+1 vote

Hi there,

I'm encountering an issue while trying to fetch the last 10 emails from a folder. Despite fetching only the last 10 emails, the results I receive seem to be sorted with mixed dates. Loading all emails and sorting them afterwards isn't an ideal solution due to performance constraints.

I've implemented a solution that relies on server-side sorting, which works well, but unfortunately, it's not supported by all mail servers.

Here's the code snippet that works only when the server supports server-side sorting:

List<long> uids = client.Search()
    .Where(Expression.Subject("subject"))
    .Sort(SortBy.Multiple(
        SortBy.Reverse(SortBy.Date()), 
        SortBy.Subject()
    ))

Could you suggest an alternative approach that ensures the last 10 emails are fetched and sorted by date, without relying on server-side sorting?

by

1 Answer

0 votes

Would simply getting 10 newest messages be good enough?

UIDs are assigned in ascending order in IMAP protocol:
https://www.limilabs.com/blog/unique-id-in-imap-protocol

...so getting all uids (just uids), sorting on client and taking 10 largest, would be the simplest way.

Remember also, that you can download Envelope only (Imap.GetEnvelopeByUID), without downloading entire email messages:
https://www.limilabs.com/blog/get-email-information-from-imap-fast

by (297k points)

When retrieving the last 10 emails from a folder, moving emails to another folder causes mixing of UIDs. This mixing process complicates the sorting of emails by date.

Each folder has its own UID sequence.

It looks like Imap.GetEnvelopeByUID may be your only option then (you can provide 'set of uids'/'range of uids' to this method).

Note, that Imap.Search, Imap.GetAll also work within a selected folder only, they don't search all folders or nested folders.

...