0 votes
by (260 points)
edited

Hi all,

We are using Rebex.mail.dll to fetch the emails from POP3 server, We have to fetch the mails based on Date instead of all the mails. So please give me some suggestions to fetch the emails based on Date using POP3..

thanks in advance...

Applies to: Rebex Secure Mail

1 Answer

0 votes
by (72.7k points)
edited

This can be easily done by the IMAP protocol while it supports SEARCH commnad. See the IMAP Searching tutorial for details.

If you can't or don't want to use IMAP protocol, you can retrieve collection of all emails headers by the GetMessageList(Pop3ListFields.FullHeaders) method, iterate thru it and retrieve only emails with desired Date:

Pop3 pop3 = new Pop3();
// connect and login

foreach (Pop3MessageInfo info in pop3.GetMessageList(Pop3ListFields.FullHeaders))
{
    if (info.Date.LocalTime > DateTime.Now.AddDays(-7))
    {
        MailMessage mail = pop3.GetMailMessage(info.SequenceNumber);
        Console.WriteLine("{0}: {1}", mail.Date, mail.Subject);
        // ...
    }
}

But it can be VERY time expensive if there is a lot of emails. Better solution, but more complicated is to retrieve info for one email at a time and finish retrieving when it is not necessary. To retrieve emails from last week you can use this approach:

Pop3 pop3 = new Pop3();
// connect and login

for (int i = pop3.GetMessageCount(); i > 0; i--)
{
    Pop3MessageInfo info = pop3.GetMessageInfo(i, Pop3ListFields.FullHeaders);
    if (info.Date.LocalTime < DateTime.Now.Date.AddDays(-7))
        break;

    MailMessage mail = pop3.GetMailMessage(info.SequenceNumber);
    Console.WriteLine("{0}: {1}", mail.Date, mail.Subject);
    // ...
}
...