Search code examples
c#outlookoffice365exchangewebservices

EWS(office 365) create Seachfolder not working


I have a program that loops all emails in Office 365 using the EWS services and if the match some criteria they get tagged with a category. I then what to create a seachfolder that looks mails that has the category.

This is my code

SearchFolder searchFolder = new SearchFolder(service);
            SearchFilter filter = new SearchFilter.ContainsSubstring(ItemSchema.Categories, categoryName);
            searchFolder.DisplayName = "Mulige CPR-data";

            searchFolder.SearchParameters.RootFolderIds.Add(WellKnownFolderName.Inbox);
            searchFolder.SearchParameters.Traversal = SearchFolderTraversal.Deep;
            searchFolder.SearchParameters.SearchFilter = filter;

            try
            {
                searchFolder.Save(WellKnownFolderName.SearchFolders);
                Console.WriteLine(searchFolder.DisplayName + " added.");
            }
            catch (Exception e)
            {
                //error handling
            }

The Seachfolder is created but when i access it in Outlook 365 I get a message saying something like "Nothing found" (I have the danish version, so not sure about the english message).

After som trial and error I found that i this instead it works fine

SearchFilter filter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "subjectTest");

So my question is why are my seachfolder not working when using categories but working fine when checking for something i the subject.

Bonus info - If I create a seachfolder in outlook using the same seach criteria(category) it works fine.


Solution

  • EWS SearchFilters don't support the logic for querying Multi-valued string properties (while the underlying Store Restriction does which is why it works in Outlook which uses MAPI). Eg your search filter won't work in a FindItem Request either. In the Microsoft Graph it seems they have supported some additional search logic so you can create Search folders that will do a MV Search eg the following would work

    https://graph.microsoft.com/v1.0/me/mailfolders('searchfolders')/childfolders
    
    
    {
        "@odata.type": "microsoft.graph.mailSearchFolder",
        "displayName": "Red Items",
        "includeNestedFolders": true,
        "sourceFolderIds": [
            "AQ.."
        ],
        "filterQuery": "categories/any(a:a eq 'Red Category')"
    }