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" permissionsConnect-ExchangeOnline -Organization "xxx.com" -Showbanner:$falseConnect-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 }}
Help Center