限制从收件箱中提取的电子邮件数量



我正在使用Microsoft.Office.Interop.Outlook并填充集合。我目前处理的一个收件箱有超过1万封电子邮件。我有没有办法限制被提取的电子邮件数量或缩小搜索范围?

public void InitializeInbox()
{
    Outlook.Application app = new Outlook.Application();
    Outlook.NameSpace outlookNs = app.GetNamespace("MAPI");
    inboxFolder = outlookNs.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
    outlookNs.SendAndReceive(true);
    foreach (object _obj in inboxFolder.Items)
    {
        if (_obj is Outlook.MailItem)
        {
            receivedEmail.Add((Outlook.MailItem) _obj);
        }
   }
    ConcurrentBag<EmailDTO> concurrentEmails = new ConcurrentBag<EmailDTO>();
    Parallel.ForEach(
        receivedEmail, mail =>
        {
            mail.ReplyAll();
            concurrentEmails.Add(
            new EmailDTO
            {
                Subject = mail.Subject,
                Sender  = mail.SenderName,
                Body    = mail.HTMLBody,
                Date    = mail.SentOn.Date
            });
        });
    Inbox = new BindableCollection<EmailDTO>(concurrentEmails.OrderByDescending(x => x.Date));
}

因此,我希望能够设置一个限制,而不是在inboxFolder.Items中搜索。例如inboxFolder.Items.Where(x => x.Date >= DateTime.Now.AddYear(-1)

我可以使用Restrict进行限制,但我只遇到了限制未读电子邮件的问题。

inbox.Items.Restrict("[Unread]=true");

我已经想好了如何限制日期,现在我该如何限制条目的数量?

按日期限制

inboxFolder.Items.Restrict("[ReceivedTime] > '" + DateTime.Now.AddYears(-1).ToString("MM/dd/yyyy HH:mm") + "'")

带有排序.的显式限制

List<Outlook.MailItem> receivedEmail = new List<Outlook.MailItem>();
const int limit = 200;
Outlook._Items items = inboxFolder.Items.Restrict("[ReceivedTime] >= '" + DateTime.Now.AddYears(-1).ToString("MM/dd/yyyy HH:mm") + "'");
items.Sort("[ReceivedTime]");
object item = items.GetNext();
int i = 1;
do
{
    // not every item is a mail item
    if (item is Outlook.MailItem)
    {
        receivedEmail.Add((Outlook.MailItem)item);
    }

    item = items.GetNext();
    i++;
} while (null != item && i < limit);

使用OOM时不要使用LINQ,如果没有限制,请使用显式的"for"循环。更好的是,使用MAPIFolder.GetTable.

您使用的限制是什么?有限制吗?你为什么叫ReolyAll?

最新更新