Exchange Web服务 - 获取附件始终为null

时间:2013-12-12 16:18:34

标签: c# .net attachment exchangewebservices

我有一个接受ExchangeWebServices.MessageType参数的方法。我正在使用此变量从邮件中获取附件。当我获得附件的内容时,它始终为null。但正在正确读取文件名。以下是我正在使用的代码:

public void StripAttachments(MessageType fullMessage)
{
    AttachmentType[] attachments = fullMessage.Attachments;

    if (attachments != null && attachments.Length > 0)
    {
        foreach (AttachmentType attachment in attachments)
        {
            if (attachment is FileAttachmentType)
            {
                FileAttachmentType file = (FileAttachmentType)attachment;

                byte[] contents = file.Content; //Always null

                try
                {
                    if(contents != null)
                    {
                        System.IO.File.WriteAllBytes(@"C:\TestLocation" + file.Name, contents); 
                    }
                }
                catch (Exception ex)
                {
                }               
            }
        }
    }
}

是否有更好的方法从特定邮件中获取附件?

1 个答案:

答案 0 :(得分:2)

尝试使用EmailMessage代替MessageType

您需要使用EmailMessage.Bind(ExchangeService, ItemId)填充附件列表并使用它们,否则将引发异常。

public void StripAttachments(ItemId id)
{
    EmailMessage email = EmailMessage.Bind(service, id)
    foreach (Attachment a in email.Attachments)
    {
        if (a is FileAttachment)
        {
            // do your thing
        }
    }
}

另请查看Getting attachments by using the EWS Managed API了解更多信息。