, , ,

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 = "[email protected]"
$emailTo = "[email protected]"
$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

 

5 responses

  1. Jeffery Hicks Avatar

    Why not simply use the Send-MailMessage cmdlet? Your suggestion is what we needed for PowerShell v1 but v2 makes this so much easiier with an actual cmdlet.

    Here’s the online help link: http://go.microsoft.com/fwlink/?LinkID=135256

  2. Malek Jakir Avatar

    Yep, agree with Jeff. Send-MailMessage does this job. BTW, thanks for your post.

  3. Christopher Avatar
    Christopher

    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!!

  4. Jonathan Avatar
    Jonathan

    its possible attach file with this script?

  5. Ievgen Avatar
    Ievgen

    Hi, thank for a post!
    What about SSL connection? SMTP server requires

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.