Graph PowerShell: Automating Junk Email Folder Cleanup

The Junk Email folder can quickly accumulate unwanted messages, consuming mailbox storage and cluttering the user experience. Automating the cleanup of the Junk Email folder can help administrators maintain a clutter-free environment, optimize mailbox performance, and streamline email management. This article provides a step-by-step guide using Graph PowerShell to clear all emails from the Junk Email folder efficiently.

The Script

Below is the Graph PowerShell script to clear all emails from the Junk Email folder of a specified user's mailbox:


# 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 to manage
$UserUPN = "user@yourtenant.onmicrosoft.com"

# Specify the folder to clear (Junk Email)
$FolderName = "Junk Email"

# Retrieve the folder ID for the specified folder
$Folder = Get-MgUserMailFolder -UserId $UserUPN -Filter "displayName eq '$FolderName'" -Select Id

if (-not $Folder) {
    Write-Output "Folder '$FolderName' not found in $UserUPN's mailbox."
    Disconnect-MgGraph
    return
}

$FolderId = $Folder.Id

# Fetch all emails in the folder
$EmailsInFolder = Get-MgUserMailFolderMessage -UserId $UserUPN -MailFolderId $FolderId -Select "id,subject"

if ($EmailsInFolder) {
    Write-Output "Found $($EmailsInFolder.Count) emails in the '$FolderName' folder. Starting cleanup..."
    
    # Loop through emails and delete each one
    foreach ($email in $EmailsInFolder) {
        Remove-MgUserMessage -UserId $UserUPN -MessageId $email.Id -ErrorAction SilentlyContinue
        Write-Output "Deleted email: $($email.Subject)"
    }

    Write-Output "All emails in the '$FolderName' folder have been deleted."
} else {
    Write-Output "No emails found in the '$FolderName' folder for $UserUPN."
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph
                            

How the Script Works

  • Connect to Microsoft Graph: The script connects to Microsoft Graph using Connect-MgGraph with the Mail.ReadWrite permission to manage mailbox content.
  • Retrieve Folder ID: The Get-MgUserMailFolder cmdlet fetches the folder ID for the Junk Email folder using the folder's display name.
  • Fetch Emails: The Get-MgUserMailFolderMessage cmdlet retrieves all emails from the Junk Email folder.
  • Delete Emails: The Remove-MgUserMessage cmdlet iterates through and deletes each email in the folder. Errors are suppressed with -ErrorAction SilentlyContinue to handle potential race conditions.
  • Disconnect from Microsoft Graph: The script ends the session with Microsoft Graph to release resources.

Further Enhancements

  • Filter Emails for Deletion: Add a filter to delete only specific emails, such as those older than a particular date:
    -Filter "receivedDateTime lt 2024-01-01T00:00:00Z"
  • Automate Cleanup Across Multiple Users: o Process multiple mailboxes by looping through a list of user UPNs stored in a CSV file:
    Import-Csv "UserList.csv" | ForEach-Object {
        $UserUPN = $_.UserPrincipalName
        # Insert script logic here
    }
  • Log Deleted Emails: Save details of deleted emails to a log file for auditing purposes:
    $EmailsInFolder | Select-Object Subject | Out-File -FilePath "JunkEmailCleanupLog.txt"
  • Confirmation Prompt: Add a user confirmation prompt before starting the deletion process:
    $Confirm = Read-Host "Are you sure you want to delete all emails in the '$FolderName' folder? (Yes/No)"
    if ($Confirm -ne "Yes") { return }
  • Scheduled Automation: Use Task Scheduler or Azure Automation to run this script periodically to keep Junk Email folders clean automatically.

Possible Errors & Solutions

Error Cause Solution
Folder Not Found The Junk Email folder does not exist or has been renamed. o Confirm the folder name matches the exact display name in the mailbox (e.g., "Junk Email").
Access Denied The user or application lacks Mail.ReadWrite permission. Assign the appropriate permission in Azure AD and ensure admin consent is provided.
No Emails Found The Junk Email folder is already empty. Verify the folder contents to ensure no emails exist before running the script.
API Throttling Too many requests sent to Microsoft Graph in a short time. Add a delay between email deletions for large folders:

Conclusion

This Graph PowerShell script provides an efficient solution for cleaning up the Junk Email folder in a user’s mailbox. It helps administrators automate routine cleanup tasks, optimize mailbox storage, and maintain a clutter-free email environment. By incorporating additional filters, logging, and automation, this script can be tailored to suit specific organizational needs.


Suggested Reading

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