Wednesday, June 25, 2014

Everyday Powershell - Part 24 - Send Email With Inline Image

Ever wanted to include inline images with an email you are sending out from a script?

We came across the requirement during our Exchange 2013 Migration.

This was ridiculously easy to achieve in Powershell 4.
Send-MailMessage -to someuser@someserver.com -From someotheruser@someserver.com -SmtpServer somemailserver -Subject "Test" -BodyAsHtml "TEST <br /><img src="attachement.png" />" -Attachments "C:\Scripts\attachement.png"

This is how we used to do it!
Add-PSSnapin Microsoft.Exchange.Management.Powershell.Admin -erroraction silentlyContinue
$smtpServer = "somemailserver"
$att = new-object Net.Mail.Attachment("c:\scripts\attachment.png")
$att.ContentId = "att"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$body = "Some Text<br />
<img src="cid:att" />"

$msg.From = "someuser@manly.nsw.gov.au"
$msg.To.Add("someotheruser@manly.nsw.gov.au")
$msg.Subject = "Some Subject" + (get-date -format yyyyMMdd)
$msg.Body = $body
$msg.IsBodyHTML = $true
$msg.Attachments.Add($att)
$smtp.Send($msg)
$att.Dispose()

UPDATE - The HTML included in the script bugged out... Will fix shortly.

UPDATE 2 - reader sivaramsharma asked if send-mailmessage could handle multiple attachments, if this interests you too head over to Part 31 where we give a useful example.