Creating a daily report with failed delivery

Hi every,

We scheduled a module in NAV 2015 to sent out invoices to our costumers from a Outlook Online account (o365). But once in a while there is a mail address that is unreachable and the mail bounce with a notification that the massage was undelivered. The address it bounce to is configured to redirect all mails to an external mail address. But I was not able to setup a rule to redirect all “none delivered notices” to the external mail address.

I came up with a temporary solution, it’s not pretty but it works and I got to practice my Powershell skill. 🙂

I created the script below, made sure the Serviceuser was allowed to use “Get-MessageTrace” by assigning “Exchange-administrator” in Office 365 Admin Portal if using an Exchange on-premise “Organization Management” should do it. When the scripts was completed I created a scheduled task to start the scripts under Actions I choice Powershell.exe with the argument -Command C:\Script\Get-MessagesTrace.ps1

$pw = convertto-securestring -AsPlainText -Force -String SetYourPasswordHere
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist,$pw
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -Credential $cred -ConnectionUri -Authentication Basic -AllowRedirection
Import-PSSession $Session
$Yesterday = (get-date (get-date).addDays(-1) -UFormat "%m/%d/%Y")
$Today = get-date -UFormat "%m/%d/%Y"
Get-MessageTrace -SenderAddress -StartDate $Yesterday -EndDate $Today -Status failed, none | Select-Object RecipientAddress, Subject, StartDate, EndDate | ConvertTo-Html | out-file -FilePath C:\temp\Abonnement.html
$body = Get-Content C:\temp\Abonnement.html -Raw
Send-MailMessage -Body $body -BodyAsHtml -Subject 'Failed addresses' -From -to -SmtpServer
Remove-PSSession $Session