我需要在收件箱中浏览所有未读邮件并为每封电子邮件下载第一个附件,我的代码可以正常工作,但仅限第一封电子邮件,为什么?
/* load all unread emails */
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, new ItemView(1));
/* loop through emails */
foreach (EmailMessage item in findResults)
{
item.Load();
/* download attachment if any */
if (item.HasAttachments && item.Attachments[0] is FileAttachment)
{
Console.WriteLine(item.Attachments[0].Name);
FileAttachment fileAttachment = item.Attachments[0] as FileAttachment;
/* download attachment to folder */
fileAttachment.Load(downloadDir + fileAttachment.Name);
}
/* mark email as read */
item.IsRead = true;
item.Update(ConflictResolutionMode.AlwaysOverwrite);
}
Console.WriteLine("Done");
在我的收件箱中设置了第一封要阅读的电子邮件,但是sript然后停止并写下#34; Done。&#34;控制台窗口。怎么了?
答案 0 :(得分:8)
问题是您只是从Exchange请求单个项目。
FindItemsResults<Item> findResults = service.FindItems(
WellKnownFolderName.Inbox,
sf,
new ItemView(1));
ItemView class构造函数将页面大小作为其参数,定义为:
搜索操作返回的最大项目数。
因此,您要求提供单个项目,这解释了您的foreach
在该项目之后完成的原因。
要对此进行测试,您只需将pageSize
增加到更合理的值,例如100或1000。
但要修复它,你应该遵循惯用的双循环:
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
FindItemsResults<Item> findResults;
ItemView view = new ItemView(100);
do {
findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);
foreach (var item in findResults.Items) {
// TODO: process the unread item as you already did
}
view.Offset = findResults.NextPageOffset;
}
while (findResults.MoreAvailable);
这里我们继续从Exchange中检索更多项目(批量为100),只要它告诉我们有更多项目可用。
答案 1 :(得分:2)
public void readMail() {
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.Credentials = new WebCredentials("uname", "password", "domain");
service.Url = new Uri("URL");
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, new ItemView(int.MaxValue));
foreach (EmailMessage item in findResults.Items)
{
item.Load();
if (item.HasAttachments)
{
foreach (var i in item.Attachments)
{
try
{
FileAttachment fileAttachment = i as FileAttachment;
fileAttachment.Load("C:\\Users\\xxxxx\\Desktop\\comstar\\Download\\test\\" + fileAttachment.Name);
}
catch(Exception e)
{
Console.Write(e);
}
}
}
//set mail as read
item.IsRead = true;
item.Update(ConflictResolutionMode.AutoResolve);
}
}