Notification of Quarantined Email in Office 365

Organizations using Exchange Online Protection for email flow would be quarantining some emails based on their requirement, sometime it may start catching incorrect emails. This is where this script will help to notify admins with email detail to keep track of quarantined emails.

    • Prerequisites :-
      • On-Premise Server to host script.
      • Service Account to run ‘task scheduler’ job.
      • Access to query quarantined emails.
    • Script
$user = "Office365AdminAccount"
$password = "xxxxxxxxxxxxxx"
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist @($user,(ConvertTo-SecureString -String $password -AsPlainText -Force))
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri -Credential $credentials -Authentication Basic -AllowRedirection

Import-PSSession $Session
$startdate = (Get-Date).Addhours(-3)
$enddate = Get-Date

#Getting quarantined message list for last 3 hours

$quarantined_emails = Get-quarantineMessage -StartReceivedDate $startdate -EndReceivedDate $enddate
$body = $quarantined_emails | Select-Object Type, Direction, SenderAddress, ReceivedTime, Subject, Expires | ConvertTo-Html -Head $a | Out-String
$count = ($quarantined_emails | Measure-Object).count
If($count -gt 5){
    $a = "
<style>BODY{font-family: Arial; font-size: 10pt;}"
    $a = $a + "TABLE{border: 1px solid black; border-collapse: collapse;}"
    $a = $a + "TH{border: 1px solid black; background: #ffbbbb; padding: 5px; }"
    $a = $a + "TD{border: 1px solid black; padding: 5px; }"
    $a = $a + "</style>

<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>"
    Send-MailMessage -From "Quarantine Alert <span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span><><span 				data-mce-type="bookmark" 				id="mce_SELREST_end" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>" -to "", ""-BodyAsHtml -subject "Quarantined Message" -body $body -smtpServer relayserverhostname

Remove-PSSession $Session
  • Configure Task Scheduler to run above script every 3 hours.
  • Sample ReportEmail

P.S. – I will later publish an article on how to schedule scripts using task scheduler and linux cron job.


Categories: Office 365

Tags: ,

Leave a Reply

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

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

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: