Photo by Digital Buggu on Pexels.com

Overview

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 https://ps.outlook.com/powershell/ -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 0){
    $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>"
    Send-MailMessage -From "Office365-Email <email@domain.com>" -to "Email1@domain.com", "Email2@domain.com", "Email3@domain.com"-BodyAsHtml -subject "Quarantined Message" -body $body -smtpServer smtprelay.learntechfuture.com
    }

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.