How To – Send an email with PowerShell
This is a quick article on how to send an email with PowerShell. The way I have done this is that I have created a Send-Email PowerShell function which can then be added to your function library and dot sourced in your PowerShell scripts.
Alternatively you could just copy paste this function directly into your script and call it from there. Either way, it is simple and it works. Plus you can send both plain-text and HTML emails. So here it is…
Function: Send an email with PowerShell
Set your SMTP Server Info
The only thing you need to do prior to using this script is just to set your SMTP server address in the function. You can do this on line 52 of the script.
Example 1: Sending a plain-text email
If you want to send a plain-text email then do something similar to the example below:
#Set our script variables
$sFrom = "my_email@mydomain"
$sTo = "your_email_1@yourdomain, your_email_2@yourdomain, your_email_3@yourdomain"
$sSubject = "This is AWESOME!"
$sBody = "Dear John `n `n"
$sBody += "I found this awesome script that will change your life! It allows your to send an email with PowerShell! `n `n"
$sBody += "Just thought I would share. `n `n"
$sBody += "Regards, `n Joe"
#Call the SendEmail function
Send-Email -EmailFrom $sFrom -EmailTo $sTo -EmailSubject $sSubject -EmailBody $sBody -EmailHTML $False
Note: If you are wondering what
Example 2: Sending a HTML email
If you want to send a HTML email then you would need to have your body in HTML as per the example below:
#Set our script variables
$sFrom = "my_email@mydomain"
$sTo = "your_email_1@yourdomain, your_email_2@yourdomain, your_email_3@yourdomain"
$sSubject = "This is AWESOME!"
$sBody = ""
$sBody += "Dear John
"
$sBody += "I found this awesome script that will change your life! It allows your to send an email with PowerShell!
"
$sBody += "Just thought I would share.
"
$sBody += "Regards,
Joe"
$sBody += "
"
#Call the SendEmail function
Send-Email -EmailFrom $sFrom -EmailTo $sTo -EmailSubject $sSubject -EmailBody $sBody -EmailHTML $True
Note: To be able to use double quotes as required for HTML attributes, you need to escape them first by putting the `
character in-front of them. This tells PowerShell to keep the double quotes as part of the string. Otherwise if you don’t do this PowerShell will assume you are ending the string and then you get all sorts of errrors.
Well that is pretty much it. How to send an email with PowerShell – both plain-text and HTML formats.
Any questions or suggestions let me know in the comments below.
Luca
Nice, easy to setup and sends without all the authentication and security problems of the default powershell send-Mailmessage cmdlet that you see many seeking an answer to (including me). This by-passes all of that. Nicely done.