如何查询Exchange邮件服务器的电子邮件项目?

时间:2014-03-10 16:34:59

标签: c# email exchangewebservices exchange-server-2010

我正在尝试升级使用WebDAV读取Exchange 2003的现有应用程序。 邮件服务器将升级到Exchange 2013,因此我正在检查如何使用EWS。

我遇到一个问题,虽然我知道收件箱中有未附加的项目附件,但我对FindItems对象运行的查询返回空...

这是我的代码段:

private static void GetAttachments(ExchangeService service)
{
    // Return a single item.
    ItemView view = new ItemView(100);
    ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);// .Exchange2007_SP1);

    service.UseDefaultCredentials = true;
    service.AutodiscoverUrl("bbtest@bocuk.local", RedirectionUrlValidationCallback);

    ItemView view = new ItemView(1);

    string querystring = "HasAttachments:true Subject:'ATTACHMENT TEST' Kind:email";

    // Find the first email message in the Inbox that has attachments. 
    // This results in a FindItem operation call to EWS.
    FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view);

    //FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Inbox, new ItemView(50));

    if (results.TotalCount > 0)
        {
            // looping through all the emails
            for (Int16 iDx = 0; iDx < results.TotalCount-1; iDx++)
            {

                EmailMessage email = results.Items[iDx] as EmailMessage;

                if (email.IsRead == false) { 

                    // Request all the attachments on the email message. This results in a GetItem operation call to EWS.
                    email.Load(new PropertySet(EmailMessageSchema.Attachments));

                    foreach (Attachment attachment in email.Attachments)
                    {
                        if (attachment is FileAttachment)
                        {
                            FileAttachment fileAttachment = attachment as FileAttachment;

我应该做的是阅读目标收件箱中的所有未读电子邮件(只有一个Exchange服务器)并将附件带到磁盘上,以便我可以将它们作为附件添加为新案例在SalesForce上。

我哪里错了?

此外,这一行:

ItemView view = new ItemView(100);

是:

ItemView view = new ItemView(1);

当然只会查找一个电子邮件项目,对吗?

1 个答案:

答案 0 :(得分:1)

我提交了以下XML并获得了预期的结果。弄清楚发生了什么的最简单方法是查看XML。

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
               xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
 <soap:Header>
    <t:RequestServerVersion Version="Exchange2010_SP2"/>
  </soap:Header>
<soap:Body>
    <FindItem xmlns="http://schemas.microsoft.com/exchange/services/2006/messages"
               xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
              Traversal="Shallow">
      <ItemShape>
        <t:BaseShape>IdOnly</t:BaseShape>
      </ItemShape>
      <ParentFolderIds>
        <t:DistinguishedFolderId Id="inbox"/>
     </ParentFolderIds>
      <QueryString>HasAttachments:true Subject:'ATTACHMENT TEST' Kind:email</QueryString>
    </FindItem>
  </soap:Body>
</soap:Envelope>