13 Feb 2012

Sending Email Using PowerShell

I’ve just been called out on the fact that I didn’t complete my mini-blog series on sending emails using PowerShell.  So, to finally conclude those articles, an example of using the Send-MailMessage cmdlet that was introduced in PowerShell V2.0.

Send-MailMessage –From "recipient@target.com" –To "sender@source.com" –Subject "Test" –Body "A test of the Send-MailMessage cmdlet"  -Attachments "c:\Attachment.xls" –SmtpServer smtpServer.com

In order to send a email with multiple attachments, you need to pass an array with the full file paths of all the attachments to the -Attachments parameter. This is easily done in PowerShell by simply piping the contents to the Send-MailMessage cmdlet.

Get-ChildItem "C:\Folder" -Include *.txt | Where {-NOT $_.PSIsContainer} | foreach {$_.fullname} |
Send-MailMessage -From "recipient@target.com" -To "sender@source.com"  -subject "Test" -smtpServer smtpServer.com

Or to send each attachment separately:

foreach ($attachment in $attachments)
{
	Send-MailMessage -From "recipient@target.com" -To "sender@source.com"  -subject "Test" -smtpServer smtpServer.com -attachments $attachment
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.