PowerShell – Sending an Email via Office 365

The following is an example of how to send an email using PowerShell via O365. If you need to send via Gmail or another provider, it should just be a case of swapping out the SMTP settings.

The email account defined with SMTPClient.Credentials will need a O365 license and will need to have permission to send from the address defined by $EmailFrom. If $EmailFrom is a different mailbox

# O365 Email setup
$SMTPServer = "smtp.office365.com" 
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 

# Change this sections variables as required 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("[email protected]", "Password"); 
$EmailFrom = "[email protected]"
$EmailTo = "[email protected]"
$EmailSubject = "Just a Test Mail"
$EmailBody = "<strong>A Test HTML Email</strong>"

# Send the Email
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$EmailSubject,$EmailBody)
$SMTPMessage.IsBodyHTML = $true # Set to $false or delete this line if you want plain text

Need a script to email users of an upcoming password expiry? PowerShell – Notify users of an upcoming AD password expiry via email

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.