Organizing Emails Using Graph PowerShell

Managing and organizing emails in Microsoft 365 can often be a time-consuming task for both users and administrators. Automating the process of moving specific emails to designated folders can significantly improve productivity and keep mailboxes organized. Microsoft Graph PowerShell allows you to streamline this task by automatically filtering and moving emails based on set conditions.

In this article, we’ll introduce a PowerShell script that leverages Microsoft Graph to move specific emails to a designated folder within a user’s mailbox. This automation is a valuable tool for administrators who want to ensure that important messages are properly organized and easily accessible.

The Script: Move Specific Emails to a Folder in a User's Mailbox

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Mail.ReadWrite.All"

# Define the user whose emails you want to manage
$UserId = "user@yourdomain.com"

# Define the subject of the email you want to move (e.g., emails containing "Important Notification")
$searchSubject = "Important Notification"

# Specify the target folder where the emails will be moved (e.g., "Important")
$targetFolderName = "Important"

# Retrieve the target folder or create it if it doesn't exist
$targetFolder = Get-MgUserMailFolder -UserId $UserId -Filter "displayName eq '$targetFolderName'"
if (-not $targetFolder) {
    $targetFolder = New-MgUserMailFolder -UserId $UserId -DisplayName $targetFolderName
}

# Retrieve emails that match the specified subject from the user's inbox
$emailsToMove = Get-MgUserMessage -UserId $UserId -Filter "contains(subject, '$searchSubject')" -Property Id Subject ReceivedDateTime

# Move the retrieved emails to the specified target folder
foreach ($email in $emailsToMove) {
    Move-MgUserMessage -UserId $UserId -MessageId $email.Id -DestinationId $targetFolder.Id
    Write-Host "Moved email: $($email.Subject)"
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph

How the Script Works

  • Connect-MgGraph: The script begins by connecting to Microsoft Graph using the Mail.ReadWrite.All permission scope, which allows the script to access and move emails within user mailboxes.
  • Define the User and Search Criteria: It specifies the UserId of the mailbox to be managed and sets the searchSubject to filter emails containing a particular keyword in the subject line.
  • Create or Retrieve the Target Folder: The script checks whether the target folder (e.g., "Important") already exists in the user’s mailbox. If it doesn't exist, the New-MgUserMailFolder cmdlet creates the folder.
  • Retrieve Specific Emails: The Get-MgUserMessage cmdlet searches for emails in the user's inbox that match the specified subject condition. It retrieves essential properties like Id, Subject, and ReceivedDateTime for each matching email.
  • Move Emails to the Target Folder: The Move-MgUserMessage cmdlet then moves each of the retrieved emails to the target folder. The script logs each moved email's subject for confirmation.
  • Disconnect-MgGraph: Finally, the script disconnects from Microsoft Graph, ensuring the session is properly closed.

Further Enhancements

  • Organize Emails for Multiple Users: Modify the script to loop through multiple users, automatically organizing emails for each user in your tenant. This approach is ideal for cleaning up shared mailboxes or specific groups of users.
  • $users = Import-Csv "C:\UsersList.csv"
    foreach ($user in $users) {
        $emailsToMove = Get-MgUserMessage -UserId $user.UserPrincipalName -Filter "contains(subject, '$searchSubject')" -Property Id Subject ReceivedDateTime
        foreach ($email in $emailsToMove) {
            Move-MgUserMessage -UserId $user.UserPrincipalName -MessageId $email.Id -DestinationId $targetFolder.Id
            Write-Host "Moved email: $($email.Subject) for user: $($user.UserPrincipalName)"
        }
    }
  • Use Additional Filters: Enhance the filtering criteria to include more specific conditions such as sender address, received date, or message importance. This helps refine the emails being organized.
  • $emailsToMove = Get-MgUserMessage -UserId $UserId -Filter "contains(subject, '$searchSubject') and importance eq 'High'"

Possible Errors & Solutions

Error Cause Solution
Insufficient privileges to complete the operation. The connected account does not have the required permissions. Ensure the account has been granted the Mail.ReadWrite.All permission in Azure AD. Admin consent is necessary for these permissions if using Application Permissions.
Folder not found. The specified target folder does not exist in the user’s mailbox. The script includes logic to create the folder if it doesn't exist, but you can manually verify that the folder creation process is successful.
Invalid filter clause. The filter condition is incorrect or improperly formatted. Double-check the syntax of the filter clause and ensure that the properties and keywords used are correct.
The term 'Move-MgUserMessage' is not recognized. The Microsoft Graph PowerShell module might not be installed or is out of date. Install or update the Microsoft Graph PowerShell module using the command Install-Module Microsoft.Graph.

Conclusion

Automating email organization using Microsoft Graph PowerShell provides administrators with a powerful way to manage the flow of messages within user mailboxes. By moving specific emails to designated folders, you can keep the inbox organized, make important emails easily accessible, and improve productivity.

This script offers a solid foundation that can be expanded upon to include more detailed criteria, support for multiple users, and scheduled automation. With Microsoft Graph PowerShell, you gain the flexibility to tailor email management to meet your organization’s unique needs.

Start implementing this automation today and experience the benefits of efficient mailbox organization within your Microsoft 365 environment!

Suggested Reading

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