Graph PowerShell: Retrieve Emails From Specific Outlook Category

Outlook categories allow users to organize emails into easily recognizable labels, enabling efficient email management. As an administrator, you may need to retrieve all emails tagged with a specific category for auditing, troubleshooting, or compliance purposes. This article provides a Graph PowerShell script to fetch and display all emails tagged with a specific category from a user’s mailbox.

The Script


# Install the Microsoft Graph PowerShell module if not already installed
# Install-Module -Name Microsoft.Graph -Scope CurrentUser

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Mail.Read"

# Specify the User Principal Name (UPN) of the mailbox to query
$UserUPN = "user@yourtenant.onmicrosoft.com"

# Specify the category to search for
$CategoryName = "Project Updates"

# Fetch emails tagged with the specified category
$CategorizedEmails = Get-MgUserMessage -UserId $UserUPN -Filter "categories/any(c:c eq '$CategoryName')" -Select "id,subject,from,receivedDateTime,categories"

# Check if any emails are found
if ($CategorizedEmails) {
    Write-Output "Found the following emails with the category '$CategoryName':"
    foreach ($email in $CategorizedEmails) {
        Write-Output "Subject: $($email.Subject)"
        Write-Output "From: $($email.From.EmailAddress.Address)"
        Write-Output "Received: $($email.ReceivedDateTime)"
        Write-Output "Categories: $($email.Categories -join ', ')"
        Write-Output "------------------------------------"
    }
} else {
    Write-Output "No emails found with the category '$CategoryName' for $UserUPN."
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph
                            

How the Script Works

  1. Connect to Microsoft Graph: The script authenticates to Microsoft Graph using the Connect-MgGraph cmdlet with the Mail.Read permission to access email data.
  2. Specify the Category: Define the desired Outlook category to filter emails, such as "Project Updates" or "Finance."
  3. Retrieve Categorized Emails: The Get-MgUserMessage cmdlet filters emails with the specified category using the categories/any OData filter.
  4. Display Results:Outputs the subject, sender, received date, and categories of all matching emails to the PowerShell console.
  5. Disconnect from Graph: o Ends the session with Microsoft Graph to release resources.

Further Enhancements

  • Export Results to CSV: Save the categorized emails to a CSV file for analysis or reporting:
    $ExportPath = "CategorizedEmails.csv"
    $CategorizedEmails | Select-Object @{Name="Sender";Expression={$_.From.EmailAddress.Address}}, Subject, ReceivedDateTime, Categories | Export-Csv -Path $ExportPath -NoTypeInformation
    Write-Output "Emails have been exported to: $ExportPath"
  • Filter by Date Range: Retrieve only recent emails tagged with the category:
    -Filter "categories/any(c:c eq '$CategoryName') and receivedDateTime ge 2024-01-01T00:00:00Z"
  • Search Across Multiple Categories: Extend the script to retrieve emails from multiple categories:
    $Categories = @("Finance", "HR", "Legal")
    foreach ($Category in $Categories) {
        # Insert script logic with $Category
  • Process Multiple Users: Iterate through multiple mailboxes using a CSV file of UPNs:
    Import-Csv "UserList.csv" | ForEach-Object {
        $UserUPN = $_.UserPrincipalName
        # Insert script logic here
    }
  • Automate Reporting: Schedule the script to run periodically and email categorized email reports to administrators.
  • Log Results: o Save results to a log file for auditing purposes:
  • $CategorizedEmails | Out-File -FilePath "CategorizedEmailsLog.txt"

Possible Errors & Solutions

Error Cause Solution
Access Denied The user or application lacks the required Mail.Read permission. Assign the necessary permission in Azure AD and ensure admin consent is provided.
Invalid Category Name The specified category does not exist in the user’s mailbox. Verify that the category exists in the mailbox by reviewing the user's Outlook settings.
No Emails Found No emails are tagged with the specified category. Confirm that emails are tagged correctly and that the category name matches exactly.
API Throttling Too many requests sent to Microsoft Graph in a short period. Add a delay between requests for large mailboxes or multiple users:
Start-Sleep -Milliseconds 500

Conclusion

This Graph PowerShell script provides a streamlined way to retrieve emails tagged with specific categories in Outlook. By leveraging this script, administrators can quickly locate and analyze categorized emails for auditing, troubleshooting, or compliance purposes. With further enhancements, the script can be tailored to meet various organizational needs, including reporting and automation.

Suggested Reading

© m365corner.com. All Rights Reserved. Design by HTML Codex