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.
# 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
$CutoffDate
variable specifies the date before which emails will be deleted.receivedDateTime lt $CutoffDate
.$OldEmails | Select-Object Subject, ReceivedDateTime | Export-Csv -Path "OldEmails.csv" -NoTypeInformation
-Filter "receivedDateTime lt $CutoffDate and isRead eq false"
Import-Csv "UserList.csv" | ForEach-Object {
$UserUPN = $_.UserPrincipalName
# Run the script logic for each mailbox
}
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. |
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