Exchange Script to remove all the emails from a Sender.

For Specific user.
Search-Mailbox -Identity "usermailboxname" -SearchQuery 'from:<sender@domain.com>' -DeleteContent
For all the Users
# Get all mailboxes
$mailboxes = Get-Mailbox -ResultSize Unlimited

foreach ($mailbox in $mailboxes) {
    $mailboxName = $mailbox.PrimarySmtpAddress
    Write-Host "Processing mailbox: $mailboxName"
    Search-Mailbox -Identity $mailboxName -SearchQuery 'from:spam email' -DeleteContent 
}

*We can use force if it is required.

# Get all mailboxes
$mailboxes = Get-Mailbox -ResultSize Unlimited

foreach ($mailbox in $mailboxes) {
    $mailboxName = $mailbox.PrimarySmtpAddress
    Write-Host "Processing mailbox: $mailboxName"
    Search-Mailbox -Identity $mailboxName -SearchQuery 'from:spam email' -DeleteContent -Force
}
For Selective users using csv file.
$csvFilePath = "C:\PATH OF THE CSV"

$users = Import-Csv -Path $csvFilePath

foreach ($user in $users) {
    $mailboxName = $user.PrimarySmtpAddress
    Write-Host "Processing mailbox: $mailboxName"
    Search-Mailbox -Identity $mailboxName -SearchQuery 'from:SPAM EMAIL' -DeleteContent 
}
To verify the deletion.
$mailboxName = "user mamilbox"

$senderEmail = "spam email"

$targetMailbox = "admin@email.com" 
$targetFolder = "SearchLogs" 

Write-Host "Processing mailbox: $mailboxName"

$searchResults = Search-Mailbox -Identity $mailboxName -SearchQuery "from:$senderEmail" -TargetMailbox "admin mailbox -TargetFolder SearchLogs -LogOnly -LogLevel Full

Please be aware of executing the PowerShell Scripts. Kindly use it at your own risk.

Leave a Comment