Graph PowerShell: How to Delete Emails Based on Sender's Email Address

Managing and maintaining a clean mailbox is a critical task for administrators. With Microsoft Graph PowerShell, you can automate email management efficiently. In this article, we’ll explore how to use a script to delete emails based on a sender’s email address.


Prerequisites

Before running the script, ensure you have the following prerequisites:

  • Install the Microsoft Graph PowerShell module: Ensure the module is installed on your system.
  • Install-Module -Name Microsoft.Graph -Scope CurrentUser
  • Permissions: Grant the Mail.ReadWrite permission for the signed-in user in Azure Active Directory.

  • Administrative Access: You must have the necessary permissions to access and manage user mailboxes.

  • User Principal Name (UPN): dentify the mailbox UPN of the user whose emails you want to manage.


The Script

Below is the PowerShell script to track the list of daily active tenant users:

# Connect to Microsoft Graph with required scopes
Connect-MgGraph -Scopes "Mail.ReadWrite"

# Specify the User Principal Name (UPN) of the mailbox to query
$UserUPN = "user@yourtenant.onmicrosoft.com"


# Specify the sender's email address
$SenderEmail = "spam@example.com"

# Search for emails sent by the specified sender
$EmailsToDelete = Get-MgUserMessage -UserId $UserUPN -Filter "from/emailAddress/address eq '$SenderEmail'" -Select "id,subject,receivedDateTime,from"


# Display emails to be deleted
if ($EmailsToDelete) {
    Write-Output "Found the following emails from '$SenderEmail':"

    foreach ($email in $EmailsToDelete) {
        Write-Output "Subject: $($email.subject)"
        Write-Output "From: $($email.from.emailAddress.address)"
        Write-Output "Received: $($email.receivedDateTime)"
        Write-Output "Message ID: $($email.Id)"
        Write-Output "------------------------------------"
    }

    # Confirm deletion
    $ConfirmDeletion = Read-Host "Do you want to delete these emails? (Y/N)"
    if ($ConfirmDeletion -eq "Y") {
        foreach ($email in $EmailsToDelete) {
            Remove-MgUserMessage -UserId $UserUPN -MessageId $email.Id -Confirm:$false
            Write-Output "Deleted email with Subject: $($email.subject)"
        }
    } else {
        Write-Output "Deletion aborted by the user."
    } 
} else {
        Write-Output "No emails found from the sender '$SenderEmail'."
}
    

Script Explanation

  1. Connect to Microsoft Graph: The script establishes a connection to Microsoft Graph with the Mail.ReadWrite permission.
  2. Define User and Sender: You specify the UPN of the mailbox and the sender’s email address whose messages you want to delete.
  3. Filter Emails: The Get-MgUserMessage cmdlet filters emails by the sender's email address using the from/emailAddress/address property.
  4. Preview Emails: The script lists all matching emails, including their subject, sender, and received date.
  5. Confirmation: It prompts the user for confirmation before proceeding with the deletion.
  6. Delete Emails: The Remove-MgUserMessage cmdlet deletes the identified emails.

Use Cases

  • Spam Cleanup: Remove emails from known spam senders or malicious addresses.
  • Mailbox Maintenance: Clear outdated or unnecessary emails from a specific sender.
  • Compliance Management: Delete emails from unauthorized or non-compliant senders.

Possible Errors and Solutions

Access Denied

  • Cause: Insufficient permissions in Microsoft Graph.
  • Solution: Assign Mail.ReadWrite permissions to the signed-in user.

Invalid Filter Clause

  • Cause: The filter syntax is incorrect.
  • Solution: Ensure the filter uses the correct property (from/emailAddress/address) and follows proper syntax.

No Matching Emails Found

  • Cause: No emails meet the specified criteria.
  • Solution: Verify the sender’s email address and adjust the query.

Cannot Find User

  • Cause: The UPN provided is incorrect or inaccessible.
  • Solution: Confirm the UPN of the user mailbox and ensure the signed-in account has access.

Conclusion

This script simplifies email management by targeting emails from a specific sender and automating their removal. With a few modifications, it can be tailored to meet different administrative requirements, such as bulk processing for multiple users. By leveraging Microsoft Graph PowerShell, administrators can streamline operations and maintain mailbox hygiene efficiently.

Feel free to try this script and let us know how it works for you! If you have additional use cases or suggestions, share them in the comments.


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

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