Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the Windows PowerShell Cookbook, 3rd edition.

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, O'Reilly, 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".

Send an Email

Problem

You want to send an email.

Solution

Use the Send-MailMessage cmdlet to send an email.

PS > Send-MailMessage -To guide@leeholmes.com `
    -From user@example.com `
    -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.

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.