Exchange/Office 365 add domains from EML files to SPAM block list

The script reads EML files from a directory and parses the header.from and adds the domain to the SPAM block list.

 <#
Stephen

Spam Filter
#>

Connect-ExchangeOnlineShell
$SpamFolder = "C:\Users\Administrator\Desktop\spam"

$DomainsNeverBlock = @('gmail.com','outlook.com','aol.com','yahoo.com')

$DefaultPolicy = Get-HostedContentFilterPolicy -Identity "Default"

$regex = [regex]"header\.from=(.*);"

Get-ChildItem -Path $SpamFolder -File | % {
    #Get-Content $_.FullName
    $from = (Get-Content $_.FullName | Select-String 'header.from')
    if($from -match $regex) {
        $domain = $Matches[1]
        if(-not $DomainsNeverBlock.Contains($domain)) {
            Write-Warning "Blocking Domain $domain"
           $DefaultPolicy | Set-HostedContentFilterPolicy -BlockedSenderDomains @{Add=$domain} -Confirm
        }
    }
}

#Sync Spam Policies
$OnPremPolicy = Get-HostedContentFilterPolicy -Identity "Cloud quarantine for on prem users"
$DefaultPolicy = Get-HostedContentFilterPolicy -Identity "Default"

$OnPremPolicy | Set-HostedContentFilterPolicy -AllowedSenderDomains $DefaultPolicy.AllowedSenderDomains -AllowedSenders $DefaultPolicy.AllowedSenders -BlockedSenders $DefaultPolicy.BlockedSenders -BlockedSenderDomains $DefaultPolicy.BlockedSenderDomains
 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.