Search code examples
outlookmicrosoft-graph-apioutlook-restapi

How to retrieve all uncategorized emails count in office 365 user mailboxes using Microsoft graph api


I'm currently working on a PowerShell script to retrieve uncategorized emails count in user mailboxes in office 365 platform. I'm using microsoft graph api to achieve this.

To explain further, office 365 gives users ability to categorize email using colors, for example for my organization, if you are done with an email, you are required to categorize with color green, if you are currently working on the email, you categorize with yellow color'.

Now i need to be able to retrieve total count of emails without categorization color.

Have tried the endpoint below, however its pulling incorrect responses.

$accessToken = "tokenhere"
$mail_user = "useremailhere"
$graphuri = "https://graph.microsoft.com/v1.0/users/$mail_user/mailfolders/Inbox/messages?$select=categories&$filter=categories/any(a:a+eq+'null+Category')&count=true"

$resp = Invoke-RestMethod -Method get -Uri $graphuri -ContentType "application/json" -Headers @{Authorization=("bearer {0}" -f $accessToken)}

$resp | fl

The endpoint keeps on returning the same message count of 124, even after going ahead and categorized more emails in that particular mailbox.

If i try to query a specific color, i get positive results using the following endpoint.


https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$select=subject,receivedDateTime,categories&$filter=categories/any(a:a+eq+'Green+Category')&count=true

What i'm i doing wrong.


Solution

  • If you want to get messages without category you need to use not operator together with any operator.

    GET https://graph.microsoft.com/v1.0/me/mailfolders/Inbox/messages?
        $select=categories&$filter=NOT(categories/any())&count=true
    
    GET https://graph.microsoft.com/v1.0/users/$mail_user/mailfolders/Inbox/messages?
        $select=categories&$filter=NOT(categories/any())&count=true
    

    I didn't specified Boolean expression inside any operator. It means that $filter=categories/any() would return all messages with any category but you need the opposite and it can be achieved by using not operator.