我正在尝试从 Exchange 获取特定用户的未读电子邮件数量。
我能够从收件箱中获取电子邮件数量,如下所示:
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
ItemView view = new ItemView(int.MaxValue);
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);
int unreadCount = 0;
foreach (EmailMessage i in findResults)
{
unreadCount++;
}
label1.Text = unreadCount.ToString();
这很好用。
我还能够获取所有子文件夹是收件箱:
FindFoldersResults findResults1 = service.FindFolders(
WellKnownFolderName.Inbox,
new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep });
foreach (Folder folder in findResults1.Folders)
{
Console.WriteLine(folder.DisplayName);
}
问题是我无法将这两者结合在一起。
我知道我可以做嵌套的 foreach 循环,但我想避免这种情况。
我发现了这些问题:Exchange Web Services (EWS) FindItems inside All Folders,但它至少需要使用 Outlook 2010 才能创建AllItems
文件夹。
我知道我可以创建SearchFilterCollection
,但如何为其添加规则,以便它在收件箱和所有子文件夹中搜索未读电子邮件?
编辑:
这是我迄今为止尝试做的:
private int getEmailCount()
{
int unreadCount = 0;
FolderView viewFolders = new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep, PropertySet = new PropertySet(BasePropertySet.IdOnly) };
ItemView viewEmails = new ItemView(int.MaxValue) { PropertySet = new PropertySet(BasePropertySet.IdOnly) };
SearchFilter unreadFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, unreadFilter, viewEmails);
unreadCount += findResults.Count();
FindFoldersResults inboxFolders = service.FindFolders(WellKnownFolderName.Inbox, viewFolders);
foreach (Folder folder in inboxFolders.Folders)
{
findResults = service.FindItems(folder.Id, unreadFilter, viewEmails);
unreadCount += findResults.Count();
}
return unreadCount;
}
基本上这是可行的,但是当我创建了多个子文件夹时,它开始工作得很慢。
我可以做一个而不是多个查询来获得相同的结果吗?