+1 vote

Is there any way we can filter the email by date. I don't want to download all the email .

by

1 Answer

0 votes
 
Best answer

Yes, you can use Search API to search using IMAP:

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

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(-3))
        );

    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

by (297k points)
edited by
...