+1 vote

Here is the code, I am using to do paging. I am showing emails in a grid, would like to pull only the 15 emails in the current page.

using (var imap = new Imap())
{
    imap.ConnectSSL(provider.EmailServer, provider.EmailPort);

    imap.SendCommand(@"ID (""GUID"" ""1"")");

    imap.Login(provider.EmailUserName, provider.EmailPassword);

    imap.SelectInbox();

    List<long> uids = imap.GetAll();

    totalMailCount = uids.Count;

    var filter = new List<long>();

    if (totalMailCount > pageSize)
    {
        filter = uids.Skip(pageNumber).Take(pageSize).ToList();
    }
    else
    {
        filter = uids;
    }

    List<MessageInfo> infos = imap.GetMessageInfoByUID(filter);

    foreach (MessageInfo info in infos)
    {
        var item = new MailItem();

        item.Subject = info.Envelope.Subject;
        var from = info.Envelope.From.First();

        item.FromEmailAddress = from.Address;
         item.FromName = from.Name;

        item.FromName = string.IsNullOrEmpty(item.FromName) ? 
             item.FromEmailAddress : 
             item.FromName;

        item.SentDate = info.Envelope.Date.Value;
        item.Id = (int)info.UID;
        item.AttachmentCount = info.BodyStructure.Attachments.Count;
        item.UIDL = info.UID.ToString();

        list.Add(item);
    }
    imap.Close();
}

Please let me know, if there is a better way to do this.

Thanks for your help, I appreciate it.

Have tried several components, so far this is the fastest.

by (250 points)

1 Answer

0 votes

Your approach looks generally OK, of course assuming you will add a while loop and take 15 element page from uids collection inside the loop.

Some thoughts though:

  • Don't cast UID to int, int is not enough to hold it.
  • Depending on your scenario, you may limit the number of uids you receive (use Imap.Search and Expression.UID), for example knowing the last one you processed you can download new ones only.
  • Are you sure ID GUID command is needed?
  • Remember you shouldn't create new connection/perform login to download each page.
by (301k points)
...