Search code examples
c#exchange-serverexchangewebservicesews-managed-api

Getting an attachment using EWS and C# failing with ServiceMethodException


So i am currently building an application that allows a group of users to view all emails from a certain email address. This all works correctly. The problem I am encountering comes when i am trying to get the attachments.

I am relatively new to this area and used the example from Microsoft found here. Compare this to my code below:

    protected internal override Stream GetAttachmentStreamFinal(MailAttachmentDetails attachment)
    {
        var response = m_service.GetAttachments(new[] { attachment.Id }, BodyType.Text, Enumerable.Empty<PropertyDefinitionBase>());
        if (response.OverallResult != ServiceResult.Success)
        {
            if (response.Count > 0)
            {
                var ex = new MailException(response[0].ErrorMessage);
                ex.Data.Add(response[0].ErrorCode, response[0].ErrorMessage);
                foreach (var ed in response[0].ErrorDetails)
                {
                    ex.Data.Add(ed.Key, ed.Value);
                }
                throw ex;
            }
            throw new MailException("Error occurred while fetching the attachment from the mail service.");
        }

        foreach (var attachmentResponse in response)
        {
            if (attachmentResponse.Attachment is FileAttachment)
            {
                var fa = attachmentResponse.Attachment as FileAttachment;
                var cs = new MemoryStream(fa.Content);
                fa.Load(cs);
                cs.Seek(0, SeekOrigin.Begin);
                return cs;
            }
        }
        return null;
    }

As you can see both sets of code are very similar. However when I step through and get to the attachmentResponse.Attachment is FileAttachment line I get this error thrown

Attempt by method 'Mail.ExchangeEmailService.GetAttachmentStreamFinal(Mail.MailAttachmentDetails)' to access method 'Microsoft.Exchange.WebServices.Data.GetAttachmentResponse.get_Attachment()' failed.

Everything is being passed in correctly and the response returns as success.

I have noticed when stepping through my code that Attachment shows as a non-public member. But as this is encapsulated in Microsofts class im unsure as to why that is the case or what i can do?


Solution

  • Make sure you have the latest version of the Microsoft.Exchange.WebServices.dll. Older versions didn't return the actual attachment data when calling that particular overload of the GetAttachments method.