Delete Emails from M365 Mailboxes with Graph PowerShell [2025 Guide]

Dealing with spam or phishing emails in a Microsoft 365 environment is a crucial responsibility for administrators. When a security threat is identified, acting quickly to remove malicious emails from user inboxes can prevent potential breaches. Microsoft Graph PowerShell makes this process more straightforward by allowing you to search for and delete specific emails directly from user mailboxes.

In this article, we’ll explore a PowerShell script that leverages Microsoft Graph to automatically find and delete emails matching specific criteria from a user’s mailbox. This script is an essential tool for administrators who want to proactively manage email security and ensure a clean and safe email environment.


The Script: Delete Specific Emails from a User's Mailbox

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Mail.ReadWrite.All"

# Define the user whose emails you want to manage
$UserId = "user@yourdomain.com"

# Define the subject of the email you want to delete (for example, emails containing "Phishing Alert")
$searchSubject = "Phishing Alert"

# Retrieve emails that match the specified subject from the user's inbox
$emailsToDelete = Get-MgUserMessage -UserId $UserId -Filter "contains(subject, '$searchSubject')" -Property Id Subject ReceivedDateTime

# Delete the retrieved emails
foreach ($email in $emailsToDelete) {
    Remove-MgUserMessage -UserId $UserId -MessageId $email.Id
    Write-Host "Deleted email: $($email.Subject)"
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph

How the Script Works

  • Connect-MgGraph: The script starts by connecting to Microsoft Graph using the Mail.ReadWrite.All permission. This level of permission is necessary to access, read, update, and delete messages in users' mailboxes.
  • Define User and Search Criteria: The UserId variable specifies the target user’s mailbox, while the searchSubject variable defines the keyword or phrase to search for in the email subject line.
  • Retrieve Specific Emails: The Get-MgUserMessage cmdlet is used to search for emails in the specified user's inbox that contain the keyword in the subject. The filter condition uses the contains function to perform a case-insensitive search.
  • Delete Matching Emails: Once the relevant emails are identified, the Remove-MgUserMessage cmdlet deletes each email from the user's mailbox. The script logs the subject of each deleted email for tracking purposes.
  • Disconnect-MgGraph: Finally, the script disconnects from Microsoft Graph to ensure the session is properly closed.

Further Enhancements

  • Bulk Email Deletion for Multiple Users: Modify the script to apply the email deletion process across multiple users in the organization. You can loop through a list of users stored in a CSV file.
  • $users = Import-Csv "C:\UsersList.csv"
    foreach ($user in $users) {
        $emailsToDelete = Get-MgUserMessage -UserId $user.UserPrincipalName -Filter "contains(subject, '$searchSubject')" -Property Id Subject ReceivedDateTime
        foreach ($email in $emailsToDelete) {
            Remove-MgUserMessage -UserId $user.UserPrincipalName -MessageId $email.Id
            Write-Host "Deleted email: $($email.Subject) for user: $($user.UserPrincipalName)"
        }
    }
  • Include Additional Filters: Enhance the script to filter emails based on other criteria, such as sender, received date, or importance level.
  • $emailsToDelete = Get-MgUserMessage -UserId $UserId -Filter "contains(subject, '$searchSubject') and from/emailAddress/address eq 'malicious@domain.com'"
  • Scheduled Automation: Set up the script to run on a schedule using Task Scheduler or Azure Automation. This can help continuously monitor and clean up emails based on specific criteria.
  • Send Activity Report: Add functionality to send a summary report to administrators once the script runs, detailing which emails were deleted and from which users' mailboxes.
  • $deletionReport = "Deleted $($emailsToDelete.Count) emails matching '$searchSubject' in $UserId's mailbox"
    Send-MailMessage -To "admin@yourdomain.com" -Subject "Email Deletion Report" -Body $deletionReport -SmtpServer "smtp.yourdomain.com"

Frequently Asked Questions

  • Can I delete emails for multiple users in one go using Graph PowerShell?
  • Yes, you can loop through a list of user mailboxes using a CSV file and automate the deletion process for each user by targeting specific folders or search criteria.

  • Does deleting an email using Graph PowerShell permanently remove it from the mailbox?
  • Not immediately. By default, the email is moved to the Deleted Items or Recoverable Items folder depending on the method used. Permanent deletion may require additional compliance or retention actions.

  • Do I need elevated permissions to delete another user’s email?
  • Yes. The account executing the script must have appropriate permissions—typically Mailbox.ReadWrite and Mail.Send Graph permissions (either delegated or application-level), and admin consent is required.

  • Is there a way to delete emails based on subject or received date?
  • Absolutely. You can filter messages using query parameters like receivedDateTime, subject, or from, and then delete only the matched messages.

Possible Errors & Solutions

Error Cause Solution
Insufficient privileges to complete the operation The connected account does not have the required permissions to delete emails. Ensure that the account has been granted the Mail.ReadWrite.All permission in Azure AD and that admin consent has been provided.
The term 'Remove-MgUserMessage' is not recognized The Microsoft Graph PowerShell module might not be installed or is not up to date. Install or update the Microsoft Graph PowerShell module by running Install-Module Microsoft.Graph.
Invalid filter clause The filter syntax might be incorrect or improperly formatted. Verify that the filter condition uses the correct syntax. Double-check the use of quotation marks and ensure that property names are correctly spelled.
No emails found matching the criteria No emails meet the specified search condition. Confirm that there are emails in the user’s inbox that match the specified subject or adjust the search criteria.

Streamline Bulk Deletion with One Query
When deleting emails across multiple users, avoid running searches per mailbox. Instead, use a single CSV with user UPNs and wrap the logic in a loop—this makes your script easier to read, debug, and maintain.
Consider Retention and Recoverability
By default, emails aren’t permanently purged—they move to the Recoverable Items folder and can be recovered within the retention period. If your goal is full removal, combine your script with compliance deletion or retention policy logic to ensure complete cleanup.

Conclusion

Using Microsoft Graph PowerShell to delete specific emails from user mailboxes provides a powerful tool for administrators to respond to security threats and manage mailbox content effectively. Whether you’re cleaning up phishing attempts or removing outdated messages, automating the email deletion process can save time and help ensure a secure email environment.

This script serves as a strong foundation that can be further enhanced to suit your organization’s needs. By utilizing Microsoft Graph, you gain granular control over email management, which plays a crucial role in maintaining your Microsoft 365 environment’s security and efficiency.

Start implementing this email cleanup automation today and take control of your organization's email hygiene with ease!

Suggested Reading

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