EWS get count of unread emails from all folders

后端 未结 4 490
我在风中等你
我在风中等你 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:23

    Here is the code for fetching the total unread count of a mailbox.

    1. Find all folders with deep traversal
    2. Limit the set of properties for each folder to id, unreadcount, displayname (forinformational purpose)
    3. Some of the folders like calendars, contacts don't have this property so handle that case

    Limitations with this code snippet:

    1. If the mailbox contains more than 1000 folders under Top of information store, then you will not get the complete total unread count
    2. To handle that case do finditems in a loop until there are no more items with same logic

    This makes only one findfolders call and work on the results.

    public static int GetTotalUnreadCount(ExchangeService ewsConnector)
    {
        int pagedView = 1000;
        FolderView fv = new FolderView(pagedView) { Traversal = Microsoft.Exchange.WebServices.Data.FolderTraversal.Deep };
        fv.PropertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.UnreadCount, FolderSchema.DisplayName);
    
        FindFoldersResults findResults = ewsConnector.FindFolders(WellKnownFolderName.MsgFolderRoot, fv);
    
        int totalUnreadCount = 0;
        foreach (Folder f in findResults.Folders)
        {
            try
            {
                totalUnreadCount += f.UnreadCount;
                Console.WriteLine("Folder [" + f.DisplayName + "] has [" + f.UnreadCount.ToString() + "] unread items.");
            }
            catch(Exception ex)
            {
                Console.WriteLine("Folder [" + f.DisplayName + "] does not have the unread property.");
            }
        }
    
        Console.WriteLine("Mailbox has [" + totalUnreadCount.ToString() + "] unread items.");
    
        return totalUnreadCount;
    }
    

提交回复
热议问题