Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

12.11 Send an Email

Problem

You want to send an email.

Solution

Use the Send-MailMessage cmdlet to send an email.

PS > Send-MailMessage -To [email protected] `
    -From [email protected] `
    -Subject "Hello!" `
    -Body "Hello, from another satisfied Cookbook reader!" `
    -SmtpServer mail.example.com

Discussion

The Send-MailMessage cmdlet supports everything you would expect an email-centric cmdlet to support: attachments, plain-text messages, HTML messages, priority, receipt requests, and more. The most difficult aspect usually is remembering the correct SMTP server to use.

The Send-MailMessage cmdlet helps solve this problem as well. If you don’t specify the -SmtpServer parameter, it uses the server specified in the $PSEmailServer variable, if any.

For most of its functionality, the Send-MailMessage cmdlet leverages the System.Net.Mail.MailMessage class from the .NET Framework. If you need functionality not exposed by the Send-MailMessage cmdlet, working with that class directly may be an option.