我想使用 EWS 托管 API 获取收件箱文件夹中的所有邮件并将它们存储为 .eml
.问题在于获取(1) 所有 邮件,其中包含(2) 所有 header (例如发件人、收件人、主题)(我保留了from
的那些值的信息) , to
和其他地方的其他属性,所以我也需要它们)和 (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);
我得到以下异常:
The property MimeContent can't be used in FindItem requests.
我不明白
(1) 这些是什么ItemSchema
和 BasePropertySet
是
(2) 以及我们应该如何使用它们
所以我删除了ItemSchema.MimeContent
:
PropertySet properties = new PropertySet(BasePropertySet.FirstClassProperties);
我编写了以下简单代码来获取收件箱中的所有邮件:
ItemView view = new ItemView(50);
view.PropertySet = properties;
FindItemsResults<Item> findResults;
List<EmailMessage> emails = new List<EmailMessage>();
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
在控制台上。所以我必须理解 pagesize
和 offset
错误的。我想明白
(3) 什么 pagesize
, offset
和 offsetbasepoint
在 ItemView
构造函数意味着
(4)他们的行为方式和
(5)如何使用它们取回收件箱中的所有邮件
我没有在网上找到任何文章很好地解释这些,只是提供了代码示例。尽管它可能会变长,但还是会欣赏问题式的解释。
最佳答案
EWS 与各种操作返回的属性有点不一致。 Item.Bind 不会返回与 FindItem 完全相同的属性。就定义您希望从服务器获得的内容而言,您正在正确使用 PropertySet,但您必须在正确的位置使用它们。您需要做的是找到项目,然后将属性加载到其中。这并不理想,但这就是 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<Item> findResults;
List<EmailMessage> emails = new List<EmailMessage>();
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 操作。
关于c# - 从 Exchange Web 服务托管 API 获取收件箱中的所有邮件并将它们存储为 .eml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20662855/