Graph PowerShell Script: Categorize Emails from a Specific Sender in Outlook

Categorizing emails from a specific sender helps users quickly identify important messages in their mailbox. This Graph PowerShell script retrieves all emails from a specified sender and assigns them a specific Outlook category for easy identification.

The Script

Below is the Graph PowerShell script that retrieves the daily email activity (sent and received emails) for specific users:


# 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.ReadWrite"
                                
# Specify the User Principal Name (UPN) of the mailbox
$UserUPN = "user@yourtenant.onmicrosoft.com"
                                
# Specify the sender email address
$SenderEmail = "important.sender@example.com"
                                
# Specify the category name to assign (must exist in Outlook)
$CategoryName = "Important Sender"
                                
# Fetch all emails from the specified sender
$Emails = Get-MgUserMessage -UserId $UserUPN -Filter "from/emailAddress/address eq '$SenderEmail'" -Select id,subject,from,categories
                                
# Check if emails from the sender exist
if ($Emails) {
        foreach ($email in $Emails) {
                try {
                    # Assign the category to the email
                    Update-MgUserMessage -UserId $UserUPN -MessageId $email.Id -BodyParameter @{categories = @($CategoryName)}
                    Write-Output "Assigned category '$CategoryName' to email: $($email.Subject)"
                } catch {
                    Write-Output "Failed to update email: $_"
                    }
                }
} else {
        Write-Output "No emails found from $SenderEmail."
}
                                
# Disconnect from Microsoft Graph
Disconnect-MgGraph

How the Script Works

  1. Connect to Microsoft Graph: Uses Connect-MgGraph with Mail.ReadWrite permissions to modify mailbox content.
  2. Filters Emails from the Specified Sender: Retrieves all emails from the specified sender using OData filtering.
  3. Assigns a Category to Matching Emails: o Updates the email’s categories property to assign it to "Important Sender".:
  4. Provides a Confirmation Message:: Displays success or failure messages for each processed email.
  5. Disconnects from Microsoft Graph:: Ends the session to free up resources.

Further Enhancements

  • Process Emails for Multiple Users If you want to categorize emails for multiple users in the organization:
  • $Users = Get-MgUser -Filter "UserType eq 'Member'" -Select Id, UserPrincipalName
    foreach ($User in $Users) {
        $UserUPN = $User.UserPrincipalName
        # Insert script logic here
    }
  • Categorize Emails from Multiple Senders: To categorize emails from multiple senders with different labels:
  • $SenderCategoryMap = @{
        "finance@example.com"  = "Finance"
        "hr@example.com"       = "HR Updates"
        "it-support@example.com" = "IT Support"
    }
                                    
    foreach ($Sender in $SenderCategoryMap.Keys) {
        $Category = $SenderCategoryMap[$Sender]
        $Emails = Get-MgUserMessage -UserId $UserUPN -Filter "from/emailAddress/address eq '$Sender'" -Select id,subject,from
                                    
        foreach ($email in $Emails) {
            Update-MgUserMessage -UserId $UserUPN -MessageId $email.Id -BodyParameter @{categories = @($Category)}
            Write-Output "Assigned category '$Category' to email: $($email.Subject)"
        }
    }
                                    
  • Export Categorized Emails to a CSV File To maintain an audit log of categorized emails:
  • $Emails | Select-Object Subject, From, Categories | Export-Csv -Path "CategorizedEmails.csv" -NoTypeInformation
  • Create a New Outlook Category if It Doesn’t Exist
  • $params = @{
        displayName = "Important Sender"
        color = "preset4"  # Choose from preset1 to preset25
    }                          
    New-MgUserOutlookMasterCategory -UserId $UserUPN -BodyParameter $params

Possible Errors & Solutions

Error Cause Solution
Access Denied (403 Forbidden) Missing Mail.ReadWrite permissions. Ensure the user has Mail.ReadWrite permissions in Azure AD.
Category Does Not Exist in Outlook The category name has not been created in Outlook. Use New-MgUserOutlookMasterCategory to create a category.
No Emails Found No emails match the sender filter. Verify that the sender's email address is correct and the mailbox contains emails.
API Throttling Too many requests sent in a short time. Introduce a small delay: Start-Sleep -Seconds 1

Conclusion

This Graph PowerShell script simplifies email categorization in Outlook by automatically tagging emails from a specific sender with a predefined category. Administrators can use this script to: i) Organize important emails automatically, ii) Process multiple users and senders efficiently, iii)Automate categorization for improved mailbox management.

Try it out in your environment and customize it based on your requirements.
Let us know if you found this useful by writing to us @ m365corner@gmail.com