Graph PowerShell: Move Emails from a Specific Sender to a Designated Folder

Organizing emails is critical for maintaining productivity and efficiency. Administrators often need to move specific emails to designated folders to help users manage their mailboxes better. This article provides a Graph PowerShell script to move emails from a particular sender to a specific folder, streamlining email organization and improving workflow.

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.ReadWrite"

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

# Specify the sender's email address to filter emails
$SenderEmail = "important.sender@example.com"

# Specify the target folder where emails should be moved
$TargetFolderName = "ImportantEmails"

# Retrieve the ID of the target folder
$TargetFolder = Get-MgUserMailFolder -UserId $UserUPN -Filter "displayName eq '$TargetFolderName'" -Select Id

if (-not $TargetFolder) {
    Write-Output "Target folder '$TargetFolderName' not found in $UserUPN's mailbox."
    Disconnect-MgGraph
    return
}

$TargetFolderId = $TargetFolder.Id

# Fetch emails from the specified sender
$EmailsToMove = Get-MgUserMessage -UserId $UserUPN -Filter "from/emailAddress/address eq '$SenderEmail'" -Select "id,subject,from"

# Check if emails are found
if ($EmailsToMove) {
    Write-Output "Found the following emails from '$SenderEmail':"
    foreach ($email in $EmailsToMove) {
        Write-Output "Subject: $($email.Subject)"
        Write-Output "Message ID: $($email.Id)"
    }

    # Move emails to the target folder
    foreach ($email in $EmailsToMove) {
        Move-MgUserMessage -UserId $UserUPN -MessageId $email.Id -DestinationId $TargetFolderId
        Write-Output "Moved email with Subject: $($email.Subject) to folder '$TargetFolderName'."
    }

    Write-Output "All matching emails have been moved."
} else {
    Write-Output "No emails found from '$SenderEmail' for $UserUPN."
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph
                            

How the Script Works

  • Connect to Microsoft Graph: The script authenticates using Connect-MgGraph with the Mail.ReadWrite permission to access and manage mailbox items.
  • Retrieve Target Folder: Searches for the target folder ($TargetFolderName) in the user's mailbox using Get-MgUserMailFolder.
  • Query Emails: Fetches all emails from the specified sender using Get-MgUserMessage with the OData filter from/emailAddress/address eq '$SenderEmail'.
  • Move Emails: Emails matching the criteria are moved to the target folder using the Move-MgUserMessage cmdlet.
  • Handle Errors: Ensures the folder exists and checks if no emails are found, providing clear error handling.
  • Disconnect: Ends the session using Disconnect-MgGraph to avoid lingering connections.

Further Enhancements

  • Create Target Folder if Missing: Automatically create the folder if it does not exist:
    if (-not $TargetFolder) {
        $TargetFolder = New-MgUserMailFolder -UserId $UserUPN -BodyParameter @{ displayName = $TargetFolderName }
        $TargetFolderId = $TargetFolder.Id
    }
    
  • Filter Additional Conditions: Filter emails by unread status or specific date ranges for more refined results:
    -Filter "from/emailAddress/address eq '$SenderEmail' and isRead eq false"
    
  • Process Multiple Users: Automate email management across multiple mailboxes using a CSV file:
    Import-Csv "UserList.csv" | ForEach-Object {
        $UserUPN = $_.UserPrincipalName
        # Insert script logic here
    }
  • Log Results: Save details of moved emails to a CSV file for auditing:
    $LogPath = "MovedEmailsLog.csv"
    $EmailsToMove | Select-Object Subject, Id, @{Name="MovedTo";Expression={$TargetFolderName}} | Export-Csv -Path $LogPath -NoTypeInformation
    
  • Automate Reporting: Send a summary of moved emails to administrators:
    Send-MailMessage -To "admin@example.com" -Subject "Moved Emails Report" -Body "The report is attached." -Attachments $LogPath

Possible Errors and Solutions

Error Cause Solution
Access Denied Insufficient permissions. Ensure the signed-in account has the Mail.ReadWrite permission.
Target Folder Not Found The specified folder does not exist in the user's mailbox. Include logic to create the folder if it doesn’t exist.
No Emails Found No emails match the filter criteria. Verify the sender's email address and ensure matching emails exist.
Message Move Failed Invalid message ID or throttling limits. Retry the operation for failed messages or implement delays to prevent throttling.

Conclusion

This Graph PowerShell script provides an efficient way to organize mailboxes by moving emails from a specific sender into a designated folder. Its flexibility allows administrators to customize filters, process multiple mailboxes, and even automate the entire workflow. By combining this script with logging and reporting, administrators can streamline email management and improve productivity.

Try this script in your environment and let us know how it simplifies mailbox organization. If you have suggestions for enhancements or additional use cases, feel free to share them!


Suggested Reading

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