2010-06-14 59 views
7

我正在编写一个简单的控制台应用程序,用于监视特定的Exchange邮箱,当收到满足特定条件的邮件时,该应用程序将下载一个XML文件附件,并且归档电子邮件。Exchange Web服务 - 处理邮件和访问附件

我已经连接到EWS正常,并且已经能够通过任何电子邮件进行循环,但是在创建可用于访问附件的EmailMessage对象时我挣扎不已。

在下面的示例代码中,EmailMessage message = EmailMessage.Bind(...)行执行时没有错误,但没有返回有效的消息,因此当我访问和属性或方法时,出现错误:'未将对象引用设置为对象的实例”。

我是新的C#更不用说EWS所以我挣扎知道从哪里开始...

代码段:

public static void FindItems() 
    { 
     try 
     { 
      ItemView view = new ItemView(10); 
      view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending); 
      view.PropertySet = new PropertySet(
       BasePropertySet.IdOnly, 
       ItemSchema.Subject, 
       ItemSchema.DateTimeReceived); 

      findResults = service.FindItems(
       WellKnownFolderName.Inbox, 
       new SearchFilter.SearchFilterCollection(
        LogicalOperator.Or, 
        new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Sales Enquiry")), 
       view); 

      log2.LogInfo("Total number of items found: " + findResults.TotalCount.ToString()); 

      foreach (Item item in findResults) 
      { 
       log2.LogInfo(item.Id); 

       EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments)); 

       Console.WriteLine(message.Subject.ToString()); 

       if (message.HasAttachments && message.Attachments[0] is FileAttachment) 
       { 
        FileAttachment fileAttachment = message.Attachments[0] as FileAttachment; 
        fileAttachment.Load("C:\\temp\\" + fileAttachment.Name); 
        fileAttachment.Load(); 
        Console.WriteLine("FileName: " + fileAttachment.FileName); 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      log2.LogError(ex.InnerException); 
     } 
    } 

我访问附件代码是直接从MSDN所以我希望这是有关于...任何想法?

+1

我不认为你能够打印主题行,因为你的属性集不包括主题。 你从Exchange返回的代码是什么? emailmessage对象是否有效? 以下可能会有所帮助:http://social.technet.microsoft.com/Forums/en/exchangesvrdevelopment/thread/1d7d0be3-1e48-43c4-b2df-f6fa5c7bf254 您不需要遍历要绑定的项目 - 尝试LoadPropertiesForItems并查看是否有效 – Chris 2010-06-20 18:25:54

回答

12

恐怕我重新探讨这个问题,并设法治愈它。不幸的是,我当时太紧迫,想回到这里并记录解决方案。已通过的时间,和我的东西我改变记忆已经渐渐淡去,但据我记得那是一个行变化:

EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.Attachments)); 

这里的关键区别是,我们已经指定BasePropertySet.FirstClassProperties作为第一个参数PropertySet,而不是我们原来的BasePropertySet.IdOnly

我原来的代码已经从网上的一个例子中解脱出来,这正是我想要实现的,所以这个例子不是很正确,或者我错误地转录了它或者误解了问题的某些方面。

0
foreach(EmailMessage message in findResults) 
{ 
    message.Load(); 

    Console.WriteLine(message.Subject.ToString()); 

    if (message.HasAttachments && message.Attachments[0] is FileAttachment) 
    { 
     FileAttachment fileAttachment = message.Attachments[0] as FileAttachment; 
     fileAttachment.Load("C:\\temp\\" + fileAttachment.Name); 
     fileAttachment.Load(); 
     Console.WriteLine("FileName: " + fileAttachment.FileName); 
    } 
} 
相关问题