Graph PowerShell: Permanently Delete Emails from Deleted Items Folder

Email management is a critical aspect of Microsoft 365 administration, especially when managing storage limits and enforcing retention policies. The "Deleted Items" folder in user mailboxes often accumulates unnecessary emails, consuming valuable space. This article introduces a Graph PowerShell script to permanently delete emails from the "Deleted Items" folder, helping administrators keep mailboxes clean and optimized.

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"

# Retrieve all emails from the "Deleted Items" folder
$DeletedItems = Get-MgUserMailFolderMessage -UserId $UserUPN -MailFolderId "DeletedItems"

# Check if there are any emails in the "Deleted Items" folder
if ($DeletedItems) {
    Write-Output "Found the following emails in the 'Deleted Items' folder:"
    foreach ($email in $DeletedItems) {
        Write-Output "Subject: $($email.Subject)"
        Write-Output "Received: $($email.ReceivedDateTime)"
        Write-Output "------------------------------------"
    }

    # Confirm permanent deletion
    $ConfirmDeletion = Read-Host "Do you want to permanently delete all emails from the 'Deleted Items' folder? (Y/N)"
    if ($ConfirmDeletion -eq "Y") {
        foreach ($email in $DeletedItems) {
            Remove-MgUserMessage -UserId $UserUPN -MessageId $email.Id -Confirm:$false
            Write-Output "Permanently deleted email with Subject: $($email.Subject)"
        }
        Write-Output "All emails in the 'Deleted Items' folder have been permanently deleted."
    } else {
        Write-Output "Deletion aborted by the user."
    }
} else {
    Write-Output "The 'Deleted Items' folder is already empty for $UserUPN."
}

Disconnect-MgGraph
                            

How the Script Works

  • Connect to Graph: The script connects to Microsoft Graph with the Mail.ReadWrite permission, allowing it to manage mailbox items.
  • Retrieve Emails: It retrieves all emails in the "Deleted Items" folder using the Get-MgUserMailFolderMessage cmdlet and the DeletedItems folder ID.
  • Display Emails: The script lists emails found in the folder, including their subject and received date.
  • Confirmation Prompt: Before proceeding, the script asks for user confirmation to avoid accidental deletions.
  • Delete Emails: It permanently deletes all emails in the folder using the Remove-MgUserMessage cmdlet.
  • Disconnect: The session ends after the cleanup process.

Further Enhancements

  • Automated Cleanup: Schedule this script to run periodically using Task Scheduler or Azure Automation Runbooks to enforce consistent cleanup policies.
  • Selective Deletion: Modify the script to delete only specific emails, such as those older than a certain date:
    $OldEmails = Get-MgUserMailFolderMessage -UserId $UserUPN -MailFolderId "DeletedItems" -Filter "receivedDateTime lt 2024-01-01T00:00:00Z"
  • Bulk Processing for Multiple Users: Use a CSV file containing a list of user mailboxes to clean up "Deleted Items" across multiple accounts:
    Import-Csv "UserList.csv" | ForEach-Object {
        $UserUPN = $_.UserPrincipalName
        # Run the script logic for each user
    }
  • Logging: Add a logging mechanism to save details of deleted emails for auditing purposes:
    $DeletedItemsLog = "DeletedItemsLog.csv"
    $DeletedItems | Export-Csv -Path $DeletedItemsLog -NoTypeInformation

Possible Errors & Solutions

Error Cause Solution
Access Denied Insufficient permissions for the signed-in user. Ensure the account has the Mail.ReadWrite permission in Azure AD.
Invalid Folder ID Incorrect or non-existent folder ID specified. Use DeletedItems as the folder ID for "Deleted Items."
Mailbox Not Found The specified user’s mailbox does not exist. Verify the UPN of the user and ensure the mailbox is active.
No Emails Found The "Deleted Items" folder is empty. Confirm with the user before running the script, or handle the empty folder gracefully (as in the script).

Conclusion

Cleaning up the "Deleted Items" folder is a common administrative task to optimize mailbox storage and enforce compliance policies. With this Graph PowerShell script, administrators can automate this process efficiently. The script is flexible, allowing for selective deletions, logging, and even bulk mailbox processing, making it a versatile tool in an administrator's arsenal.

Try this script in your environment, and feel free to customize it to suit your organization's needs. Share your feedback or suggestions for further improvements!

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