PoshTip #8 – Send emails from the console
A useful technique for every sysadmin is to be able to send an email message from PowerShell.
Send-MailMessage
This cmdlet permit to send an email message with a single line of code. Below is an example :
Send-MailMessage -to "dest@get-cmd.com" -from "Contact <contact@get-cmd.com>" -Subject "My subject" -body "Test body for Send-MailMessage"
.NET objects : MailMessage and SmtpClient
We will import two .NET objects and fill the properties of the email (From, To, Smtp Server …)
$smtpServer = "smtp.server.com" $smtpFrom = "contact@get-cmd.com" $smtpTo = "dest@get-cmd.com" $msgSubject = "My subject" $msgBody = "This is an example message" $msg = New-Object System.Net.Mail.MailMessage $smtpFrom, $smtpTo, $msgSubject, $msgBody $smtp = New-Object Net.Mail.SmtpClient $smtpServer $smtp.Send($msg)