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.
# 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
Mail.ReadWrite.All
permission. This level of permission is necessary to access, read, update, and delete messages in users' mailboxes.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.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.Remove-MgUserMessage
cmdlet deletes each email from the user's mailbox. The script logs the subject of each deleted email for tracking purposes.$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)"
}
}
$emailsToDelete = Get-MgUserMessage -UserId $UserId -Filter "contains(subject, '$searchSubject') and from/emailAddress/address eq 'malicious@domain.com'"
$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"
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.
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.
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.
Absolutely. You can filter messages using query parameters like receivedDateTime
, subject
, or from
, and then delete only the matched messages.
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. |
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!
© m365corner.com. All Rights Reserved. Design by HTML Codex