Send-MailMessage

Understanding the Power of Send-MailMessage in PowerShell

Welcome back to Wahmans Powershell blog! Today we’re diving into one of the most essential and flexible cmdlets available when automating communications from your scripts: Send-MailMessage. As the name implies, this cmdlet sends email messages directly from your PowerShell session.

The official Microsoft description is simple and to the point: Sends an email message. But the real-world applications of this tiny cmdlet are vast — from simple notifications to fully integrated monitoring solutions. Let’s go through four examples ranging from beginner to advanced use so you can fully understand the power behind Send-MailMessage.

Before You Start

To use Send-MailMessage, you’ll need access to an SMTP server. Many organizations have one, or you can use public services like Gmail (with proper configuration).

Example 1: Basic Email Notification

This is the simplest use: send an email with a subject and body.

Send-MailMessage -From "[email protected]" -To "[email protected]" -Subject "Hello World" -Body "This is a test email from PowerShell." -SmtpServer "smtp.example.com"

Example 2: Send an Email with an Attachment

You may want to send logs or reports via email. Here’s how to attach a file:

Send-MailMessage -From "[email protected]" -To "[email protected]" `
    -Subject "Nightly Report" -Body "Please find the report attached." `
    -Attachments "C:\Reports\NightlyReport.pdf" -SmtpServer "smtp.example.com"

Example 3: Using HTML Body for a Richer Email

Want your emails to look more professional? Try HTML formatting.

$html = @"
<h1>Server Status Report</h1>
<p>Everything is running smoothly.</p>
"@

Send-MailMessage -From "[email protected]" -To "[email protected]" `
    -Subject "HTML Report" -Body $html -BodyAsHtml -SmtpServer "smtp.example.com"

Example 4: Dynamic Alerts in a Monitoring Script

In a real-world scenario, you might want to notify IT when a service is down.

$serviceName = "Spooler"
$service = Get-Service -Name $serviceName

if ($service.Status -ne 'Running') {
    $body = "Service $serviceName is not running. Current status: $($service.Status)"
    Send-MailMessage -From "[email protected]" -To "[email protected]" `
        -Subject "Service Alert: $serviceName" -Body $body -SmtpServer "smtp.example.com"
}

Final Thoughts

Whether you’re just starting out with PowerShell or crafting enterprise-grade scripts, Send-MailMessage is a critical cmdlet to keep in your toolbox. With just a few lines of code, you can integrate seamless email communication into any of your processes.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *