0 votes
by (200 points)

Hi,

Iam using Rebex secure mail(Imap) for crawling folders in gmail account.

I have a code like this [ for getting mails for past 30 days ]:

parameters = new ImapSearchParameter[] { 
    ImapSearchParameter.Arrived(DateTime.Now.AddDays(-30), 
    DateTime.Now.AddDays(1))
};

ImapMessageCollection tLatestMessages =
    cImap.Search(ImapListFields.UniqueId, parameters);

The order of messages in the collection is not as expected.

I expect the order as per the date with which they arrived, but I am getting in the order with which they are added to the folder.

Please clarify if I am missing any thing

Applies to: Rebex Secure Mail

1 Answer

0 votes
by (144k points)

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);
    }
}       
...