我已经在解决这个问题已有一段时间了,但未能在线找到有效的答案。我正在使用Exchange EWS API进行一些电子邮件处理。我需要处理的事情之一是带有附件的EmailMessage。这些附件之一恰好是另一个EmailMessage。我将其称为附件EmailMessage。

我想将此EmailMessage转换为byte [],但是每次尝试,都会出现异常。下面是我的代码:

if (((ItemAttachment)attachment).Item is EmailMessage)
{
     EmailMessage msg = ((ItemAttachment)attachment).Item as EmailMessage;
     msg.Load(new PropertySet(ItemSchema.MimeContent));
     byte[] content = msg.MimeContent.Content;
}


问题是无论我尝试加载什么,都会抛出异常


  Microsoft.Exchange.WebServices.dll中发生类型'System.InvalidOperationException'的异常,但未在用户代码中处理
  
  附加信息:附件不支持此操作。


如果不调用msg.Load(),则会收到另一个错误消息,提示我需要加载内容。

我不明白如果我对未附加任何内容的EmailMessage进行相同的操作,则效果很好。为什么在某个时间点EmailMessage是附件很重要?如何获得EWS / .NET /无论抛出什么异常,将附加的EmailMessage视为EmailMessage而不是ItemAttachment?

最佳答案

您需要对具有包含MimeContent的属性集的嵌入式附件上的每个附件使用GetAttachments操作。例如,类似的东西(如果您处理多个消息,则可以通过将GetAttachment请求分组来提高效率)。

            PropertySet psPropSet = new PropertySet(BasePropertySet.FirstClassProperties);
        psPropSet.Add(ItemSchema.MimeContent);
        foreach (Attachment attachment in CurrentMessage.Attachments)
        {
            if (attachment is ItemAttachment)
            {
                attachment.Load();
                if (((ItemAttachment)attachment).Item is EmailMessage)
                {
                    EmailMessage ebMessage = ((ItemAttachment)attachment).Item as EmailMessage;
                    foreach (Attachment ebAttachment in ebMessage.Attachments)
                    {
                        if (ebAttachment is ItemAttachment)
                        {
                            Attachment[] LoadAttachments = new Attachment[1];
                            LoadAttachments[0] = ebAttachment;
                            ServiceResponseCollection<GetAttachmentResponse> getAttachmentresps = service.GetAttachments(LoadAttachments, BodyType.HTML, psPropSet);
                            foreach (GetAttachmentResponse grResp in getAttachmentresps)
                            {
                                EmailMessage msg = ((ItemAttachment)grResp.Attachment).Item as EmailMessage;
                                msg.Load(new PropertySet(ItemSchema.MimeContent));
                                byte[] content = msg.MimeContent.Content;
                            }
                        }
                    }

                }
            }
        }

10-07 13:15