Script to Retrieve and Delete Emails Using Exchange Online and Microsoft Graph API

1 min. readlast update: 09.26.2024

This script connects to Exchange Online and Microsoft Graph using an app registration with "Mail.ReadWrite" permissions. It retrieves emails sent from a specific sender address using the Get-MessageTrace cmdlet. For each email, it attempts to find the corresponding message in the user's mailbox via the Graph API by filtering on the InternetMessageId. If the message is found, it deletes the email from the user's mailbox. This script is useful for selectively deleting messages from Exchange Online mailboxes.

Here is the script:

#Need to create App Reg with "Mail.ReadWrite" permissions
Connect-ExchangeOnline -Organization "xxx.com" -Showbanner:$false
Connect-MgGraph -TenantId "xxx.com" -ClientId "xxx" -CertificateThumbprint "xx"

$emails =  Get-MessageTrace -SenderAddress "spam.co.il"
$emails | ForEach-Object{

    $from = $_.RecipientAddress
    $InternetMessageId = $_.MessageId

    $Message = Get-MgUserMessage -UserId $from -Filter "InternetMessageId eq '$InternetMessageId'" -ErrorAction SilentlyContinue
    if($Message){
        Write-Output "Deleting  $Message.Subject from $from"
        Remove-MgUserMessage -MessageId $Message.Id -UserId $from
    }
}

Was this article helpful?