Sending Email to Office 365 with Powershell

Any decent server administrator will have a bunch of Powershell scripts automating tasks on your server.

We have tasks to delete historic database backups and delete historic website log files and the like.

You want to know if your script has succeeded or failed so you can do something about it. Firstly you must set up a unique password for this application (because as a system admin you have three factor authentication (TFA) on your account...of course you do, yes!?) and if you have TFA enabled then your usual password won't work. It will also change regularly.

Likely your SMTP servername is


Port 587


To get a password logon to, go to...


  • My account
  • Security and privacy
  • Additional security verification
  • Create and manage app passwords


Create a new password specifically for this service/server.

The following example is a script that clears down old database backups after 7 days, and emails you if there is a problem.

# Ps1-script to keep azure storageaccount for managed backups clean
$secpasswd = ConvertTo-SecureString "password for your smtp server" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ("office365 username", $secpasswd)

Import-Module Azure

$storageAccount = ""
$storageKey = ""
$blobContainer = ""

$CleanupTime = [DateTime]::UtcNow.AddDays(-7)
$context = New-AzureStorageContext -StorageAccountName $storageAccount -StorageAccountKey $storageKey
Get-AzureStorageBlob -Container $blobContainer -Context $context |
Where-Object { $_.LastModified.UtcDateTime -lt $CleanupTime -and $_.BlobType -eq "PageBlob" -and $_.Name -like "*.bak"} |
$CleanupTime = [DateTime]::UtcNow.AddDays(-7)
Get-AzureStorageBlob -Container $blobContainer -Context $context |
Where-Object { $_.LastModified.UtcDateTime -lt $CleanupTime -and $_.BlobType -eq "PageBlob" -and $_.Name -like "*.log"} |

$SuccessMailParams = @{
To = ''
From = ''
Subject = 'Clear DB Backup Success'
Body = 'The script ran successfully'

Send-MailMessage @SuccessMailParams -Port 587 -SmtpServer -UseSsl -Credential $creds
catch {
$FailMailParams = @{
To = ''
From = ''
Subject = 'Clear Old DB Backup Failed'
Body = 'There was an error with the script!!'

Send-MailMessage @FailMailParams -Port 587 -SmtpServer -UseSsl -Credential $creds