I get asked quite often to show examples of sending an email from Powershell. This could easily by written into an actual cmdlet, and it wouldn’t shock me a bit if it already has. Either way, its very simple .Net code to send email.
In this script sample below, I am showing a small utility type of script (could be easily made a function) that can be used almost like an “out-email” type of cmdlet.
Warning, I haven’t tested this Script extensively at all. I know the .Net classes definitely work, but in this example, I tried to get a bit fancy with the body where the script can work with a param or pipeline input and in my limited testing I encountered some inconsistency. Just the same, this is still a neat sample of the types of scripts you would write to accomplish a task like this. Also, before you can run this, you should consider making edits to the param defaults and such as well. This is by no means a production level script is just a concept demonstration.
#This script can be used either at the end of a pipe or all by itself
# here is a pipe example:
# get-process | send-email -to email@example.com -subject "Process List Report"
# or this script can be run by itself
# send-email -to firstname.lastname@example.org -from email@example.com -subject "Powershell Email" -body "Hey there buddy!"
# Define Parameters
param ( [string]$subject = "PowerShell Notification",
[string]$to = $(throw "We can use a lot of defaults here, but pal, we need to have a TO address for this email."),
[string]$from = "$env:username@$env:userdomain.com",
[string]$smtpserver = "defaultinternalsmtpserver.company.com",
[string]$body = "No Body Entered",
$pipelineinput = $input
# See if a body was explicity entered as a Parameter, if not check if there is pipeline input, if not then no body
if ( $body -eq "No Body Entered" )
If ($pipelineinput -ne "")
[string]$body = $input
[string]$body = "No Message Body Supplied by Sender!"
# Create Message Object
$msg = new-object System.Net.Mail.MailMessage $from, $to, $subject, $body
# Create SMTP Client object to get ready to send message
$client = new-object System.Net.Mail.SmtpClient $smtpserver
# Use Default Creds instead of anonymous if desired
$client.UseDefaultCredentials = $true
This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm.