Graph PowerShell: Find and Delete Emails Older Than a Specific Date

Managing email retention is a vital responsibility for administrators to maintain compliance and optimize mailbox storage. Automating the deletion of old emails helps enforce retention policies and reduces clutter in user mailboxes. This article introduces a Graph PowerShell script to identify and permanently delete emails older than a specified date.

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

# Specify the cutoff date for deletion
$CutoffDate = "2024-01-01T00:00:00Z"

# Fetch all emails older than the specified date
$OldEmails = Get-MgUserMessage -UserId $UserUPN -Filter "receivedDateTime lt $CutoffDate" -Select "id,subject,receivedDateTime"

# Check if any emails match the criteria
if ($OldEmails) {
    Write-Output "Found emails older than $CutoffDate:"
    foreach ($email in $OldEmails) {
        Write-Output "Subject: $($email.Subject)"
        Write-Output "Received: $($email.ReceivedDateTime)"
        Remove-MgUserMessage -UserId $UserUPN -MessageId $email.Id -Confirm:$false
    }
} else {
    Write-Output "No emails found older than $CutoffDate for $UserUPN."
}

Disconnect-MgGraph
                            

How the Script Works

  • Connect to Microsoft Graph: The script uses the Connect-MgGraph cmdlet with the Mail.ReadWrite permission to authenticate and access mailbox messages.
  • Define a Cutoff Date: The $CutoffDate variable specifies the date before which emails will be deleted.
  • Retrieve Old Emails: The Get-MgUserMessage cmdlet retrieves emails received before the cutoff date using the OData filter receivedDateTime lt $CutoffDate.
  • Display Email Details: The script lists the matching emails, showing their subject, received date, and message ID for review.
  • Confirm and Delete Emails: After confirmation, the Remove-MgUserMessage cmdlet permanently deletes the identified emails.
  • Disconnect from Graph: Ends the session to ensure no lingering connections.

Further Enhancements

  • Export Email List Before Deletion: Save the details of the emails to a CSV file for review:
    $OldEmails | Select-Object Subject, ReceivedDateTime | Export-Csv -Path "OldEmails.csv" -NoTypeInformation
  • Apply Additional Filters: Combine filters to refine the search. For example, delete only unread emails older than the cutoff date:
    -Filter "receivedDateTime lt $CutoffDate and isRead eq false"
  • Process Multiple Mailboxes: Use a CSV file to iterate through multiple mailboxes:
    Import-Csv "UserList.csv" | ForEach-Object {
        $UserUPN = $_.UserPrincipalName
        # Run the script logic for each mailbox
    }
  • Automate the Script: Schedule the script using Task Scheduler or an Azure Automation Runbook to run periodically.

Possible Errors & Solutions

Error Cause Solution
Access Denied The account lacks the required permissions. Ensure the Mail.ReadWrite permission is granted in Azure AD.
Invalid Filter Clause Syntax issues in the OData filter query. Verify the syntax for date filters (e.g., receivedDateTime lt YYYY-MM-DDTHH:MM:SSZ).
No Emails Found No emails match the criteria. Verify the cutoff date and adjust filters if necessary.
Cannot Locate Mailbox The user principal name is incorrect or inaccessible. Confirm the UPN is accurate and that the mailbox exists.

Conclusion

This Graph PowerShell script is a powerful tool for administrators to enforce email retention policies and optimize mailbox storage. By automating the deletion of emails older than a specified date, it simplifies management tasks while ensuring compliance. The flexibility to customize filters and process multiple mailboxes makes this script a valuable asset in any administrator's toolkit.

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