msgbartop
Everybody get your shell on!
msgbarbottom

Sending an email with Powershell

This is a handy little function that sends an email using the System.Net.Mail namespace found in .NET 2.0. Can be used for pretty much anything; I use it primarily for error notification if one of my engineers runs a script that fails. It can also send an attachment so you can auto-spam your coworkers with pictures of midgets.

Configuration is pretty straight forward; Supply the $sender, $recipient, $CC, and $BCC email addresses (if you want to CC or BCC anyone), the $mailserver that the script will use to send the mail, and the $subject of the email. In the $body, type or script out the body of the email. For $attachment, define the location of the attachment (if you want to send one). Besides authentication, which we will cover below, thats it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function SendMail{
$sender = "sender@mail.com"
$recipient = "recipient@mail.com"
$CC = "CCRecipient@mail.com"
$BCC = "BCCRecipient@mail.com"
$mailserver = "mailserver.domain.com"
$subject = "Subject Line of the Email"
 
$body = @"
You can type whatever you want in the body of the email here, 
including variables and error logs (useful for error notification).
This variable pulls the last error message written to the error stream and puts it in the 
body of the email which comes in handy:
 
$($Error[0])
"@
 
$msg = new-object System.Net.Mail.MailMessage $sender, $recipient, $subject, $body
$attachment = new-object System.Net.Mail.Attachment c:\midget.jpg
$msg.CC.Add($CC)
$msg.BCC.Add($BCC)
$msg.Attachments.Add($attachment)
$client = new-object System.Net.Mail.SmtpClient $mailserver

The last thing that needs to be configured is authentication. There are two primary classes I use, the NetworkCredential class which allows you to set credentials:

24
$client.Credentials = [System.Net.NetworkCredential]::("username", "password")

…and the CredentialCache class which uses your current credentials (or can be used for SMTP servers that allow anonymous authentication to send or relay mail):

24
$client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

The last line takes the $client object that we’ve built to define an SMTP server and authentication method, and the $msg object that we’ve built which contains the email properties, and sends it out:

25
$client.Send($msg)}

Done! Now you can fire off scripts, head to the pub, and get notified if your script bombs.
beer

  • Twitter
  • Facebook
  • LinkedIn
  • Digg
  • Google Bookmarks
  • Slashdot
  • StumbleUpon
  • Live
  • FriendFeed
  • Ping.fm
  • Print
  • email
  • PDF
  • RSS

Tags:

Reader's Comments

  1. |

    I really don’t like the midget comment!! Very offensive!

    Reply to this comment
  2. |

    Sending E-mail some times produces errors in connection.

    Reply to this comment

Leave a Comment