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 smtp.office365.com

 

Port 587

 

To get a password logon to office.com, 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)

try
{
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"} |
Remove-AzureStorageBlob
$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"} |
Remove-AzureStorageBlob

$SuccessMailParams = @{
To = 'support@yourco.co.uk'
From = 'support@yourco.co.uk'
Subject = 'Clear DB Backup Success'
Body = 'The script ran successfully'
}


Send-MailMessage @SuccessMailParams -Port 587 -SmtpServer smtp.office365.com -UseSsl -Credential $creds
}
catch {
$FailMailParams = @{
To = 'support@yourco.co.uk'
From = 'support@yourco.co.uk'
Subject = 'Clear Old DB Backup Failed'
Body = 'There was an error with the script!!'
}

Send-MailMessage @FailMailParams -Port 587 -SmtpServer smtp.office365.com -UseSsl -Credential $creds
}