Tuesday, January 11, 2011

Send E-Mail from PowerShell

One of the easiest and most common things I have my PowerShell scripts do is inform me and/or interested parties that they have completed a task and deliver some sort of information back via e-mail such as an Excel document. Below is a function I wrote that I "dot source" in my PowerShell scripts. You can take this code and test it out by replacing the information in the Parameters section. You may want to add some error detection in your script to ensure that at least the To:, CC: or BCC: is populated, ping the mail server and ensure that there is a subject and message before you pass the variables to the function. No error checking is done within the function.
Function Send-EMail($from,$to,$cc,$bcc,$subject,$priority,$html,$message,$mailAttachments,$smtpServer) {
  $mailMessage = New-Object System.Net.Mail.MailMessage

  $mailMessage.From = $from

  foreach($person in $to) {

  if($cc -ne $null) {
    foreach($person in $cc) {

  if($bcc -ne $null) {
    foreach($person in $bcc) {

  if($priority -eq "Normal" -or $priority -eq "Low" -or $priority -eq "High") {
    $mailMessage.Priority = $Priority
  } else {
    $mailMessage.Priority = "Normal"

  $mailMessage.Subject = $subject
  $mailMessage.Body = ($message | Out-String)
  $mailMessage.IsBodyHTML = $html

  if($mailAttachments.count -gt 0) {
    foreach($mailAttachment in $mailAttachments) {
    if(Test-Path -path $mailAttachment) {
      $attachment = New-Object System.Net.Mail.Attachment $mailAttachment

  $smtpClient = New-Object Net.Mail.SmtpClient($smtpServer)

# Parameters
$smtpServer = "mailserver.ad.yourdomain.local"

$from = "yourscript@yourdomain.local"
$to = @("you@yourdomain.local","admin1@yourdomain.local","interestedparty@theirdomain.local")
$cc = @("someoneelse@yourdomain.local")
$bcc = @("yourboss@yourdomain.local","yourclient@theirdomain.local")

$subject = "E-Mail from your PowerShell Script"

$priority = "Low" # 'High' & 'Normal'

$html = $false # Or $true
# I like to use an array to think of each line of the message as an element in the array
$message = @()
$message += "Dear Administrator,"
$message += ""
$message += "I want you to know that thing you wanted me to do is now complete. Here is your report"
$message += "containing the stuff you need to know."
$message += ""
$message += "Your automated pal,"
$message += "  Scheduled Task"

$mailAttachments = @("\\server.ad.yourdomain.local\reports\ThatStuffYouNeededToKnow.xlsx")

Send-EMail $from $to $cc $bcc $subject $priority $html $message $mailAttachments $smtpServer

No comments:

Post a Comment