General Blog

Importing Email Addresses & Domains to Blacklist in Office 365 Using PowerShell


Preparing the List

I recently had to migrate away from our third-party spam filter. I was able to get them to send us a CSV file that contains a list of all our blocked domains/email addresses, but that list was not very clean.

For example, it looked like this with a mix of domains and email addresses.

In order to make this work, I needed to clean up the list to extract emails to one file, and domains to another. To do that, I used the following commands within Kali Linux to make two new files; one that contains a list of emails, and a 2nd that contains a list of domains.

cat tmp.txt | grep @ | sort -u > emails.txt

cat tmp.txt | grep -v @ | sort -u > domains.txt


The PowerShell Section

Regardless which of the below scripts you use, you’ll need to connect to Exchange Online using something like the below.

$UserCredential = Get-Credential
$Session = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential –Authentication Basic -AllowRedirection
Import-PSSession $Session

Importing Domains to Block List

With our lists ready, I used the following code to import the domains.

$domains = "C:\temp\domains.txt" # EDIT THIS

$count = 1
foreach ($content in ($total = get-content $domains)){
	$totalcount = $total.count
	Set-HostedContentFilterPolicy -Identity Default –BlockedSenderDomains @{add=$content}
	write-host "Added $count entries of $totalcount : $content"
	$count += 1
}

Importing Emails to Block List

With our lists ready, I used the following code to import the email addresses.

$emails = "C:\temp\emails.txt" # CHANGE THIS

$count = 1
foreach ($content in ($total = get-content $emails)){
	$totalcount = $total.count
	Set-HostedContentFilterPolicy -Identity Default –BlockedSenders @{add=$content}
	write-host "Added $count entries of $totalcount : $content"
	$count += 1
}


How do we know this worked?

Let’s head over to the Exchange Admin Center. From there, we’ll go into Protection and find the Spam Filter.

Open up the Default policy and head over to the Block Lists. You should see your entries here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s