[HOWTO] Send emails via SMTP in PowerShell

This week I was tasked with testing office 365 SMTP credentials. To do so, I used PowerShell.

Inspired by How to Send Emails in C# .NET via SMTP I ended up with the following code.

$senderEmailAddress = "SENDER_EMAIL_ADDRESS"
$receiverEmailAddress = "RECEIVER_EMAIL_ADDRESS"
$subject = "Test subject"
$message = "Test message"

$imapServer = "smtp.office365.com"
$smtpClient = [System.Net.Mail.SmtpClient]::new($imapServer)

$credential = [System.Net.NetworkCredential]::new("USERNAME", "PASSWORD")
$smtpClient.Credentials = $credential
$smtpClient.UseDefaultCredentials = $false
$smtpClient.EnableSsl = $true
$smtpClient.Port = 587

$mailMessage = [System.Net.Mail.MailMessage]::new($senderEmailAddress, $receiverEmailAddress, $subject, $message)
$smtpClient.Send($mailMessage)

Credits to How to Send Emails in C# .NET via SMTP for inspiration!

IMPORTANT NOTE
Daniel Bloch kindly pointed out to me in a comment on LinkedIn that basic authentication for SMTP AUTH will be deprecated by end of April 2026. See here for more details. In the Microsoft environment, I therefore recommend sending emails via Graph API.

Leave a comment

Website Powered by WordPress.com.

Up ↑