Hi,
The Imap
objects retains the original message order as received from the IMAP server. This is usually sorted by unique ID, which explains why you are getting the messages in order with which they were added.
There is an IMAP extension that adds sorting capabilities to search queries, but this is not supported by Gmail.
This means that if you need a particular order of messages, you have to sort the collection yourself. However, to make this possible, you would have to retrieve the Envelope
info, which would make the Search
a much more expensive operation because envelope information for all the messages would have to be retrieved in addition to unique IDs.
To achieve this, use the following code:
parameters = new ImapSearchParameter[] {
ImapSearchParameter.Arrived(DateTime.Now.AddDays(-30),
DateTime.Now.AddDays(1))
};
ImapMessageCollection tLatestMessages =
cImap.Search(ImapListFields.UniqueId | ImapListFields.Envelope, parameters);
tLatestMessages.Sort(new ImapDateComparer());
With the following sorting object:
public class ImapDateComparer : System.Collections.IComparer
{
public int Compare(object o1, object o2)
{
var i1 = (ImapMessageInfo)o1;
var i2 = (ImapMessageInfo)o2
if (i1.Date == null)
return (i2.Date == null) ? 0 : -1;
if (i2.Date == null)
return 1;
return DateTime.Compare(i1.Date.UniversalTime, i2.Date.UniversalTime);
}
}