PowerShell Office 365: SMTP Email Sent with PowerShell via Office 365

In this example, I have an extremely simple function called MyCode. The purpose of the function is only to demonstrate us taking any PowerShell output then passing it ot the body of an email and sending that email.

Here is a look at the output:

Once we have the output from MyCode it is all about how we pass that over to the email. That is achieved by using Send-MailMessage.

There are a lot of required parameters when using Send-EmailMessage so using a hash table called mailprops is a simple and tidy approach to doing that.

Once mailprops is loaded, we will assign the content of that to a variable called $body

This means all that is left to do is send an email and authenticate. Give it a try yourself

Function MyCode {

    Get-WmiObject -Class Win32_Computersystem -ComputerName localhost


$mailprops = @{
    From        = 'user@website.com'
    To          = 'user@mail.com'
    Subject     = 'SMTP Email Sent with PowerShell via Office 365'
    SMTPServer  = 'smtp.office365.com'
    Port        = '587'
    UseSSL      = $true 

$userid = 'user@website.com'
$body = MyCode | Out-String
Send-MailMessage -Body $body @mailprops -Credential (Get-Credential $userid)


Would you like to buy Alan a coffee?

Visit the AlanPs1 Ko-fi page