Using powershell to send an email using SMTP
A question was posed recently in an online forum asking to fix a script used for sending email using powershell.
It got me thinking about how useful it could be to have a script build and send an email based on the results of a script.
Note that if you are using powershell v2, there is a built in command called Send-MailMessage which allows you to do this natively without the need for a function. See http://technet.microsoft.com/en-us/library/dd347693.aspx
For powershell v1, below is a simplified and easy Function you can include in a powershell script to email you. You can call the function at various stages of your script or build a log and send at the end of the script.
Whatever email system you use, it will be important that you have the relevant permissions in place to either submit mail to local recipients or relay to external addresses. If we are talking about Exchange 2007/2010 the easiest way will be to create a Receive connector specifically for the script and set to ‘Externally secured’ and use the source IP to restrict access to it. This will allow trouble free relay. You can set the port to 26 and then amend the script to read $smtpclient.port=26
** Ensure you never allow unauthorised access to an ‘Externally Secured’ receive connector! **
The script function can be placed anywhere in your script, you could place this at the bottom of your scripts if you like:
Param ($Subject, $Body)
$message = New-Object Net.Mail.MailMessage
$message.From = “email@example.com”
$message.Body = $Body
$message.Subject = $Subject
$smtpclient = New-Object Net.Mail.SmtpClient(“NAME_OR_IP_OF_SMTP_SERVER”)
Now, to call the function and send an email message simply supply the subject and body of the email and then call the function as below:
$Subject = “Subject of the message goes here”
$Body = “Body of the message goes here”
EmailResults $Subject $Body