使用 EWS C# 检索未读电子邮件

Retrieving Unread Emails with EWS C#

下面是我的工作代码片段,它从收件箱下的自定义文件夹名称中检索未读电子邮件。

foreach (Microsoft.Exchange.WebServices.Data.Folder folder in findFolderResults.Folders)
{
    LogFile.AppendLog(folder.DisplayName + " folder found in Inbox.");
    if (folder.DisplayName == folderName)
    {
        LogFile.AppendLog(folder.DisplayName + " matches " + folderName);
        ItemView view = new ItemView(emailBatch);

        do
        {
            LogFile.AppendLog("Checking for unread emails in folder " + folder.DisplayName);
            emailItemList = service.FindItems(folder.Id, sf, view);
            foreach (var emailItem in emailItemList.Items)
            {
                LogFile.AppendLog("Getting unread emails in folder " + folder.DisplayName);
                EmailMessage email = EmailMessage.Bind(service, emailItem.Id);
                retrievedEmailList.Add((EmailMessage)email);
            }

            if (!emailItemList.NextPageOffset.HasValue)
                break;
        }
        while (emailItemList.MoreAvailable);
    }
}

有一个变量 emailBatch 当前被配置为 10

我明白这意味着它只会一次性检查和检索 10 封未读电子邮件。 但是,一旦 10 邮件被添加到列表中,它会继续检查未读邮件吗?

如果发生这种情况,我需要将所有未读电子邮件添加到 retrievedEmailList,而不仅仅是 10 封电子邮件。

谢谢。

您需要实施 paged searching。您似乎已经部分尝试过这个,但是您的代码缺少一些东西。我已经更新了您的代码并添加了注释来解释我添加的新代码。

// Set the offset for the paged search.
int offset = 0;
// Set the flag that indicates whether to continue iterating through additional pages.
bool MoreItems = true;

LogFile.AppendLog(folder.DisplayName + " folder found in Inbox.");
if (folder.DisplayName == folderName)
{
    // Continue paging while there are more items to page.
    while (MoreItems)
    {
        LogFile.AppendLog(folder.DisplayName + " matches " + folderName);
        // Set the ItemView with the page size and offset.
        ItemView view = new ItemView(emailBatch, offset, OffsetBasePoint.Beginning);

        LogFile.AppendLog("Checking for unread emails in folder " + folder.DisplayName);
        emailItemList = service.FindItems(folder.Id, sf, view);
        foreach (var emailItem in emailItemList.Items)
        {
            LogFile.AppendLog("Getting unread emails in folder " + folder.DisplayName);
            EmailMessage email = EmailMessage.Bind(service, emailItem.Id);
            retrievedEmailList.Add((EmailMessage)email);
        }

        // Set the flag to discontinue paging.
        if (!emailItemList.MoreAvailable)
            MoreItems = false;
        // Update the offset if there are more items to page.
        if (MoreItems)
            offset += pageSize;
    }
}