Search code examples
c#exchangewebservices

Getting IEnumerable<Microsof.Exchange.WebService.Data.ItemId> from FindItems using EWS API


I'm writing a C# app to go through some monitoring mailboxes and clear out emails that are older than a specified period (e.g. 6 months).

Previously I was going to get the items, then in a foreach block, delete each one in turn. Looking for a solution to another issue, I stumbled upon using DeleteItems. This expects a System.Collection.Generic.IENumerable<Microsoft.Exchange.WebServices.Data.ItemId> but in the code below, FindItems returns a System.Collections.ObjectModel.Collecion<Microsoft.Exchange.WebServices.Data.Item>.

How would I convert or get the correct type to pass to DeleteItems?

ExtendedPropertyDefinition allFoldersType = new ExtendedPropertyDefinition(13825, MapiPropertyType.Integer);

FolderId rootFolderId = new FolderId(WellKnownFolderName.Root);
FolderView folderView = new FolderView(1000);
folderView.Traversal = FolderTraversal.Deep;

SearchFilter.SearchFilterCollection searchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
searchFilterCollection.Add(new SearchFilter.IsEqualTo(allFoldersType, "2"));
searchFilterCollection.Add(new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "allitems"));

FindFoldersResults findFoldersResults = exchangeService.FindFolders(rootFolderId, searchFilterCollection, folderView);

Folder allItemsFolder = findFoldersResults.Folders[0];

searchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
searchFilterCollection.Add(new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, DateTime.Now.AddMonths(-6)));
searchFilterCollection.Add(new SearchFilter.IsEqualTo(ItemSchema.ItemClass, "IPM.Note"));

var findItems = allItemsFolder.FindItems(searchFilterCollection, new ItemView(100));
var items = findItems.Items;

exchangeService.DeleteItems(findItems, DeleteMode.HardDelete, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.SpecifiedOccurrenceOnly);

Solution

  • Each Item has an Id property of type ItemId, it can be accessed using linq:

    var findItems = allItemsFolder.FindItems(searchFilterCollection, new ItemView(100));
    var itemIds = findItems.Items.Select(item => item.Id);
    
    exchangeService.DeleteItems(itemIds, DeleteMode.HardDelete, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.SpecifiedOccurrenceOnly);
    

    Item Docs: microsoft.exchange.webservices.data.item

    Item Id Docs: Microsoft_Exchange_WebServices_Data_Item_Id