EWS get count of unread emails from all folders

后端 未结 4 491
我在风中等你
我在风中等你 2021-01-01 02:03

I\'m trying to get number of unread emails from Exchange for specific user.

I\'m able to get number of emails from Inbox like so:

SearchFilter sf = n         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-01 02:28

    I've searched a bit and created this function:

        public void getEmailCount(Action callback)
        {
            int unreadCount = 0;
    
            FolderView viewFolders = new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep, PropertySet = new PropertySet(BasePropertySet.IdOnly) };
            ItemView viewEmails = new ItemView(int.MaxValue) { PropertySet = new PropertySet(BasePropertySet.IdOnly) };
            SearchFilter unreadFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            SearchFilter folderFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "AllItems"));
    
            FindFoldersResults inboxFolders = service.FindFolders(WellKnownFolderName.Root, folderFilter, viewFolders);
    
            if (inboxFolders.Count() == 0)//if we don't have AllItems folder
            {
                //search all items in Inbox and subfolders
                FindItemsResults findResults = service.FindItems(WellKnownFolderName.Inbox, unreadFilter, viewEmails);
                unreadCount += findResults.Count();
    
                inboxFolders = service.FindFolders(WellKnownFolderName.Inbox, viewFolders);
                foreach (Folder folder in inboxFolders.Folders)
                {
                    findResults = service.FindItems(folder.Id, unreadFilter, viewEmails);
                    unreadCount += findResults.Count();
                }
            }
            else //AllItems is avilable
            {
                foreach (Folder folder in inboxFolders.Folders)
                {
                    FindItemsResults findResults = service.FindItems(folder.Id, unreadFilter, viewEmails);
                    unreadCount += findResults.Count();
                }
            }
    
            callback(unreadCount);
        }
    

    Basically it checks if we have AllItems folder avilable.
    If YES then we do one, simple query that returns all unread messages.
    If NO then we loop all folders inside Inbox. This is slower and depends on how many folders and levels we have.

    Any fixes and improvements are welcome :)

提交回复
热议问题