Shak Ham
Shak Ham

Reputation: 1269

Retrieve attachments from EWS at once using EWS Managed API 2.0

I'm using EWS in order to retrieve emails, but when I want to retrieve the attachments I have to call the following function for each:

fileAttachment.Load();

Everytime I do that, it goes to the server. Is it possible to retrieve all the attachments at once? Also, is it possible to retrieve all the attachments for several mail items?

Upvotes: 0

Views: 589

Answers (1)

Glen Scales
Glen Scales

Reputation: 22032

The ExchangeService object has a GetAttachments method which basically allows you to do a batch GetAttachment request. So if you want to load the attachments on several messages at once you need to do something like (first call loadpropertiesforitems which does a batch GetItem to get the AttachmentIds)

        FindItemsResults<Item> fItems = service.FindItems(WellKnownFolderName.Inbox,new ItemView(10));
        PropertySet psSet = new PropertySet(BasePropertySet.FirstClassProperties);
        service.LoadPropertiesForItems(fItems.Items, psSet);
        List<Attachment> atAttachmentsList = new List<Attachment>();
        foreach(Item ibItem in fItems.Items){
            foreach(Attachment at in ibItem.Attachments){
                atAttachmentsList.Add(at);
            }
        }
        ServiceResponseCollection<GetAttachmentResponse> gaResponses = service.GetAttachments(atAttachmentsList.ToArray(), BodyType.HTML, null);
        foreach (GetAttachmentResponse gaResp in gaResponses)
        {
            if (gaResp.Result == ServiceResult.Success)
            {
                if (gaResp.Attachment is FileAttachment)
                {
                    Console.WriteLine("File Attachment");
                }
                if (gaResp.Attachment is ItemAttachment)
                {
                    Console.WriteLine("Item Attachment");
                }
            }
        }

Cheers Glen

Upvotes: 1

Related Questions