Send E-Mail from Powershell

Powershell Header

This is a small script which you can use to send E-Mail from Windows Powershell. This script has an hardcoded password variable because this solution is mostly used for automation. But you could also use the get-credentials command to get the credentials from a user.

# Configuration
$emailFrom = "user@mydomain.com"
$emailTo = "user@yourdomain.com"
$emailSubject = "my subject"
$emailMessage = "my message"
$smtpServer = "mail.server.com"
$smtpUserName = "username" # This could be also in e-mail address format
$smtpPassword = "password"
$smtpDomain = ""

# SMTP Object
$smtp = New-Object System.Net.Mail.SmtpClient($smtpServer)
$mailCredentials = New-Object System.Net.NetworkCredential
$mailCredentials.Domain = $smtpDomain
$mailCredentials.UserName = $smtpUserName
$mailCredentials.Password = $smtpPassword
$smtp.Credentials = $mailCredentials

# Send E-Mail
$smtp.Send($emailFrom, $emailTo, $emailSubject, $emailMessage)

Update:

Thanks to Jeffery Hicks for correcting me, since Powershell v2 there is a much easier way to send a Mail with the Send-MailMessage cmdlet. http://go.microsoft.com/fwlink/?LinkID=135256

 

Related Posts:

3 thoughts on “Send E-Mail from Powershell

  1. Thanks for the fix for version1. I have that on some old servers and needed it. Googled all over and yours was the only one that worked!!

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>