Send Email using PowerShell

While this isn’t directly related to SharePoint, there may be some times that you need to run a long running operation with PowerShell and would like to receive an email notification when the operation is completed. Here is a quick function you can place into most any script and then call to send notifications.

Since most SharePoint implementations are already configured to allow email notifications to be sent (alerts) you may be able to allow your scripts to also send you alerts. Here’s the script:

function send-notification($subject, $detail) {
    $message = New-Object System.Net.Mail.MailMessage
    $message.Subject = $subject
    $message.Body = $detail
    $message.To.Add("recipient@domain.com")
    $message.From = "sender@domain.com"
    
    $client = New-Object System.Net.Mail.SMTPClient -ArgumentList "smtp.domain.com"
    $client.Send($message)
}

To make use of the function, just simply call it with the necessary parameters:

send-notification -subject "$dbname Attached" -detail "The content database $dbname has completed the database attach upgrade. Please review the logs in Central Administration as soon as possible."

Enjoy!

Edit 12/8/2011: If you would like to send to multiple users, you can do the following:

$message.To.Add("nextemail@domain.com")
$message.To.Add("anotherperson@domain.com")
#You can also CC and BCC
$message.Cc.Add("firstcc@domain.com")
$message.Bcc.Add("firstbcc@domain.com")
Advertisements

2 thoughts on “Send Email using PowerShell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s