从Exchange Web服务托管API获取收件箱中的所有邮件,并将其存储为.eml文件

我想使用EWS托管API获取收件箱文件夹中的所有邮件,并将它们存储为.eml 。 问题在于获取(1)所有邮件(2)所有标题(如from,to,subject) (我在其他地方保留fromto和其他属性的值的信息,所以我也需要它们)和(3)byte[] EmailMessage.MimeContent.Content 。 其实我对此缺乏了解

  • Microsoft.Exchange.WebServices.Data.ItemView
  • Microsoft.Exchange.WebServices.Data.BasePropertySet
  • Microsoft.Exchange.WebServices.Data.ItemSchema

这就是为什么我发现它很难。

我的主要代码是:

当我按如下方式创建PropertySet

 PropertySet properties = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.MimeContent); 

我得到以下exception:

 The property MimeContent can't be used in FindItem requests. 

我不明白

(1)这些ItemSchemaBasePropertySet是什么

(2)我们应该如何使用它们

所以我删除了ItemSchema.MimeContent

 PropertySet properties = new PropertySet(BasePropertySet.FirstClassProperties); 

我编写了简单的以下代码来获取收件箱中的所有邮件:

 ItemView view = new ItemView(50); view.PropertySet = properties; FindItemsResults findResults; List emails = new List(); do { findResults = service.FindItems(WellKnownFolderName.Inbox, view); foreach (var item in findResults.Items) { emails.Add((EmailMessage)item); } Console.WriteLine("Loop"); view.Offset = 50; } while (findResults.MoreAvailable); 

上面我将ItemView页面大小保持为50,一次检索不超过50封邮件,然后将其抵消50以获得下一封50封邮件(如果有的话)。 然而,它进入无限循环并在控制台上连续打印Loop 。 所以我必须理解pagesizeoffset错误。 我想明白

(3) ItemView构造函数中的pagesizeoffsetoffsetbasepoint意味着什么

(4)他们的表现如何

(5)如何使用它们来检索收件箱中的所有邮件

我没有在网上发现任何文章,很好地解释这些,但只是提供代码示例。 尽管可能需要很长时间,但仍会欣赏有问题的解释。

EWS与各种操作返回的属性有点不一致。 Item.Bind不会返回与FindItem完全相同的属性。 您正确使用PropertySets,只要在服务器上定义您想要的内容,但您必须在正确的位置使用它们。 您需要做的是找到项目,然后将属性加载到它们中。 它并不理想,但这就是EWS的工作方式。 有了你的循环,当你需要将它增加50时,你会不断地为你的偏移分配50。在我的头顶,这样的事情会:

 int offset = 0; int pageSize = 50; bool more = true; ItemView view = new ItemView(pageSize, offset, OffsetBasePoint.Beginning); view.PropertySet = PropertySet.IdOnly; FindItemsResults findResults; List emails = new List(); while(more){ findResults = service.FindItems(WellKnownFolderName.Inbox, view); foreach (var item in findResults.Items){ emails.Add((EmailMessage)item); } more = findResults.MoreAvailable; if (more){ view.Offset += pageSize; } } PropertySet properties = (BasePropertySet.FirstClassProperties); //A PropertySet with the explicit properties you want goes here service.LoadPropertiesForItems(emails, properties); 

现在,您拥有了所有具有所请求属性的项目。 FindItems通常不会返回您想要的所有属性,因此最初只加载Id然后加载您想要的属性通常是要走的路。 您可能还希望以某种方式批量加载属性,具体取决于您要检索的电子邮件数量,可能在将其添加到EmailMessages列表之前的循环中。 您还可以考虑其他获取项目的方法,例如service.SyncFolder操作。