+1 vote

Can you pull emails for the last 5 days? Can you pull emails by date desc? new email first?

by

1 Answer

0 votes
 
Best answer

You should use Search for that:
https://www.limilabs.com/blog/how-to-search-imap-in-net

List<long> uids = imap.Search().Where(
    Expression.SentSince(DateTime.Now.AddDays(-5))
    );

There are several date related search expressions, that allow searching for emails within a specified range.

  • Since: Finds emails whose internal date (assigned by IMAP server on
    receive) (disregarding time and timezone) is equal or later than the
    date specified .

  • Before: Finds emails whose internal date (disregarding time and timezone) is earlier than the date specified.

  • SentSince: Finds emails whose 'Date:' header (disregarding time and timezone) is equal or later than the date specified .

  • SentBefore: Finds emails whose 'Date:' header (disregarding time and timezone) is earlier than the date specified.

Entire code that performs the search using IMAP looks like this:

using (Imap imap = new Imap())
{
    imap.ConnectSSL("imap.example.com");
    imap.UseBestLogin("user@example.com", "password");

    List<long> uids = imap.Search().Where(
        Expression.SentSince(DateTime.Now.AddDays(-5))
        );

    foreach (long uid in uids)
    {
        IMail email = new MailBuilder().CreateFromEml(
            imap.GetMessageByUID(uid));

        string subject = email.Subject;
        string text = email.Text;
    }

    imap.Close();
}

You can also consider using UNSEEN flag:
https://www.limilabs.com/blog/get-new-emails-using-imap

or remembering last processed UID:
https://www.limilabs.com/blog/get-new-emails-using-imap

As for sorting: uids are assigned by the server in ascending order (newer emails have higher uid), so the simplest solution is to sort uids list.

by (297k points)
...