customer relationships

O365: Delete specific email from sender to mailboxes

Here’s a PowerShell script that uses the Exchange Online PowerShell module to delete a specific email from multiple mailboxes. This script searches for an email with the specified subject line sent from the specified sender and deletes it.

Before running the script, ensure you have the Exchange Online PowerShell module installed and have the necessary permissions to search and delete emails in the target mailboxes.

powershellCopy code# Import the Exchange Online module
Import-Module ExchangeOnlineManagement

# Connect to Exchange Online
Connect-ExchangeOnline -UserPrincipalName -ShowProgress $true

# Define the sender and subject line
$sender = ""
$subject = "Subject line title"

# Create a unique name for the compliance search
$searchName = "DeleteSpecificEmailSearch"
$actionName = "DeleteSpecificEmailAction"

# List of mailboxes to search
$mailboxes = @("", "", "")

# Create a compliance search
New-ComplianceSearch -Name $searchName -ExchangeLocation $mailboxes -ContentMatchQuery "From:$sender AND Subject:$subject"

# Start the compliance search
Start-ComplianceSearch -Identity $searchName

# Wait for the search to complete (adjust the sleep time as necessary)
Start-Sleep -Seconds 60

# Check the status of the search
$searchStatus = Get-ComplianceSearch -Identity $searchName
if ($searchStatus.Status -eq "Completed") {
    # Create a compliance search action to delete the emails
    New-ComplianceSearchAction -SearchName $searchName -Purge -PurgeType HardDelete
    Write-Host "Emails deleted successfully."
} else {
    Write-Host "Search did not complete successfully. Please check the search status."

# Cleanup (optional)
# Remove-ComplianceSearch -Identity $searchName
# Remove-ComplianceSearchAction -Identity $actionName

# Disconnect from Exchange Online
Disconnect-ExchangeOnline -Confirm:$false

Note: Adjust the sleep time based on the expected time for the search to complete. You can also implement a loop to check the status periodically instead of using a fixed sleep time.

one click social media designs

Leave a Reply

Your email address will not be published. Required fields are marked *