Search attachments from a mailbox using EWS Managed API and C#

1.5k Views Asked by At

I want to search all attachments from a mailbox having certain keywords in their name.I am doing this using C# EWS Managed API(version 2.2). I am able to access the Item with attachments using Item.HasAttachment:true property and the code is working as expected. But the processing time is very long.

The current process flow is : 1.Get all the folders from a mailbox. 2.For each folder, search items having attchments (using Item.HasAttachment:true searcFilter). 3.Check whether the Attachment name contains the keywords.

I need to know if there is a better and faster way to access attachments in a mailbox/folder using EWS. Instead of checking every mail item, is there a way to apply filter for attachments on folder level?

Below is the code snippet used to fetch the attachemnts by name keyword

SearchFilter searchFilter = new SearchFilter.IsEqualTo(ItemSchema.HasAttachments, true); //SearchFilter for finding item with attachments FindItemsResults<Item> searchResults = null; FileAttachment fileAttachmentobj = null; ItemAttachment itemAttachmentobj = null; for (var j = 0; j < folder.Count; j++) //Looping for all the folders in a mailbox { for (int i = 0; i < strAttachNameKeyword.Length; i++) //Looping for keywords to be searched { searchResults = service.FindItems(folder[j].Id, searchFilter, view); if (searchResults.TotalCount > 0) { service.LoadPropertiesForItems(searchResults, new PropertySet(BasePropertySet.IdOnly, ItemSchema.HasAttachments)); foreach (Item item in searchResults) //Processing each item in SearchResults { item.Load(); foreach (Attachment attachmentObj in item.Attachments) //for each attachment in an item { //attachmentObj.Load(); fileAttachmentobj = attachmentObj as FileAttachment; itemAttachmentobj = attachmentObj as ItemAttachment; if (fileAttachmentobj != null && (fileAttachmentobj.Name.Contains(strAttachNameKeyword[i]))) { //fileAttachmentobj.Load(); Console.WriteLine(fileAttachmentobj.Name); Console.WriteLine(fileAttachmentobj.Size); Console.WriteLine(fileAttachmentobj.Id); } } } } } }
1

There are 1 best solutions below

2
On

I'd suggest you use a QueryString instead of a SearchFilter which means you'll be doing a Content Index search rather the a folder restriction which is much faster. eg

FindItemsResults fiItems = service.FindItems(QueryFolder, "Attachment:blah.pdf", iv);

You can easily test this using the EWSEditor https://github.com/dseph/EwsEditor/releases if you right click a folder->search for items and select the AQS radio button it has a simple interface for AQS/KQL queries