Friday, February 13, 2015

Everyday Powershell - Part 31 - Send email with multiple attachments

So back in Part 24 reader sivaramsharma asked if send-mailmessage could handle multiple attachments so we threw together this post...

$files = get-childitem C:\reports | where name -like "*.png"
$body = @()
$attachments = @()
foreach($file in $files){
    $filename = [system.io.path]::GetFileName($file.FullName)
    $attachments += $file.fullname
    $body += "TEST <br />
<img src='" + $filename + "'/>TEST <br />"
}
$body = $body | Out-String
Send-MailMessage -to someuser@someserver.com -From someotheruser@someserver.com -SmtpServer somemailserver -Subject "Test" -BodyAsHtml $body -Attachments $attachments

It's a neat little example of generating some HTML in a loop then sending it off using send-mailmessage.

4 comments:

  1. Thank you. This is exactly what I was looking for !!

    ReplyDelete
  2. Thank you Ben. Have been looking for this all over. I can now enjoy my rest if the weekend.

    ReplyDelete
  3. I am trying to attach files that is generated daily. Each file name has a different startname_yyyymmdd_*****.txt and they are all in the same path. I am using the $emailMessage.attachments.Add("C:\Folder_Test\Outbox\Archive\startname_Type1_20190307_200001.txt'). The filename changes daily when it is created as it pulls in the datetime. I need to get the files generated for the previous day and add it to the powershell query to send an email with these attachments.

    Can you please help, I have tried for quite some time.

    Thanks

    ReplyDelete