Question

I have a method which accepts a ExchangeWebServices.MessageType parameter. I am using this variable to get the attachments from the message. When I get the contents of the attachments, it is always null. But file name is being read correctly. Below is the code I am using:

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)
                {
                }               
            }
        }
    }
}

Is there a better method to get the attachments from a specific message?

Was it helpful?

Solution

Try using EmailMessage instead of MessageType

You will need to use EmailMessage.Bind(ExchangeService, ItemId) to populate the list of attachments and work with them, otherwise an exception will be thrown.

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

Also check out Getting attachments by using the EWS Managed API for more of an idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top