Office 365: Add Anti-Spoofing Protection Transport Rule with PowerShell

Modified on Tue, 21 Apr at 11:18 PM

This will send to quarantine e-mails from *@domain.com to *@domain.com which came from outside the organization and failed SPF.

# https://admin.exchange.microsoft.com/#/transportrules

Connect-ExchangeOnline

$AcceptedDomains = Get-AcceptedDomain

foreach ($DomainEntry in $AcceptedDomains) {
    $DomainName = $DomainEntry.DomainName
    
    # Skip the default Microsoft domains
    if ($DomainName -like "*.onmicrosoft.com") {
        continue
    }

    $RuleName = "Anti-Spoofing Protection - $DomainName"

    # Check if a rule with this name already exists
    if (Get-TransportRule -Identity $RuleName -ErrorAction SilentlyContinue) {
        Write-Host "Rule already exists for $DomainName. Skipping..." -ForegroundColor Yellow
    }
    else {
        Write-Host "Creating rule for $DomainName..." -ForegroundColor Cyan
        New-TransportRule -Name $RuleName `
            -SenderDomainIs $DomainName `
            -FromScope "NotInOrganization" `
            -Quarantine $true `
            -ExceptIfHeaderContainsMessageHeader "Authentication-Results" `
            -ExceptIfHeaderContainsWords "spf=pass"
    }
}

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article