+1 vote

I have a question regarding downloading of emails when I am using imap is there a functionality or parameter which I can use so that when I am downloading emails from any account I can specify the number of past days which it should check.
eg if I want to download unread emails for last 3 days only then how can I set the days to 3?

Your response at the earliest would be greatly appreciated.

by

1 Answer

0 votes
 
Best answer

You should use Imap.Search method for that. It issues SEARCH command to the IMAP server.

There are two ways of searching by date: using "Date: " email header and using internal date which IMAP server assigns to every email on arrival. Those dates may be different due to timezones, or Date header not being set or set incorrectly. Generally speaking internal server date is more reliable

Here's the code:

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

    client.SelectInbox();

    // to search using "Date: " header
    List<long> uids = client.Search(Expression.SentSince(DateTime.Now.AddDays(-3)));

    // to search using internal IMAP's server date
    //List<long> uids = client.Search(Expression.Since(DateTime.Now.AddDays(-3)));

    foreach (long uid in uids)
    {
        IMail mail = new MailBuilder().CreateFromEml(
            client.GetMessageByUID(uid));
        string subject = mail.Subject;
    }
    client.Close();
}

Remember that all search is done on the IMAP server side and that
according to IMAP standard server is required to disregard time and
timezone of any date it uses.

References:
https://www.limilabs.com/blog/how-to-search-imap-in-net

by (301k points)
selected by
...