Scripting. Powershell, VMware, Windows, Active Directory & Exchange. All that kind of stuff…..
RSS icon Email icon Home icon
  • PowerShell 2.0: One Cmdlet at a Time #2 Send-MailMessage

    Posted on November 13th, 2009 Jonathan Medd No comments

    Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Send-MailMessage cmdlet.

    What can I do with it?

    Send an email message using a specific SMTP server, from within a script or at the commaned line.

    Example:

    Send-MailMessage -to "Joe Bloggs <joe.bloggs@test.local>" -from "Jane Smith <jane.smith@test.local>" 
    -subject "Reporting Document" -body "Here's the document you wanted" -Attachment "C:\Report.doc"
    -smtpServer smtp.test.local

    How could I have done this in PowerShell 1.0?

    You could have used the .NET System.Net.Mail class

    Function SendEmail ()
    {
    param ($Sender,$Recipient,$Attachment)

    $smtpServer = smtp.test.local

    $msg = new-object System.Net.Mail.MailMessage
    $att = new-object System.Net.Mail.Attachment($attachment)
    $smtp = new-object System.Net.Mail.SmtpClient($smtpServer)

    $msg.From = $Sender
    $msg.To.Add($Recipient)
    $msg.Subject = Reporting Document
    $msg.Body = Here’s the document you wanted.
    $msg.Attachments.Add($att)


    $smtp.Send($msg)

    $att.Dispose();

    }

    SendEmail ‘jane.smith@test.local’ ‘joe.bloggs@test.local’ ‘C:\Report.doc’

    1000 things 1% better!

    Leave a reply