Skip to content

Instantly share code, notes, and snippets.

@bobalob
Created November 2, 2016 20:29
Show Gist options
  • Save bobalob/a83acac63faf4e1dfdd0c51c2274b276 to your computer and use it in GitHub Desktop.
Save bobalob/a83acac63faf4e1dfdd0c51c2274b276 to your computer and use it in GitHub Desktop.
Generate Inline Images for an email in PowerShell
Param(
[Parameter(Mandatory = $true)] $imagePathArray,
[Parameter(Mandatory = $true)] $emailFrom,
[Parameter(Mandatory = $true)] $emailSubject,
[Parameter(Mandatory = $true)] $smtpServer,
[Parameter(Mandatory = $true)] $SendTo,
$emailBodyTitle=$emailSubject
)
if (!($imagePathArray.Gettype().BaseType.Name -eq "Array")) {
Write-Host "ImagePathArray must be of type Array"
break
}
if (!($imagePathArray[0].Gettype().Name -eq "String")) {
Write-Host "ImagePathArray elements must be of type String"
break
}
#Create new mail
$eMail = New-Object system.net.mail.mailmessage
$body = "<p style='font-family: Calibri, sans-serif'>"
$body += "<br /> <u> <font size='6'> $($emailBodyTitle) </font> </u> <br /> <br />"
$counter=1
$attachArray=@()
foreach ($Image in $imagePathArray) {
#Embed Image
$tempAttach = new-object Net.Mail.Attachment($Image)
$tempAttach.ContentType.MediaType = "image/png"
$tempAttach.ContentId = "Attachment" + $Counter
#Add attachment to the mail
$eMail.Attachments.Add($tempAttach)
#Mail body
$body += "<img src='cid:$($tempAttach.ContentId)' /><br />"
$attachArray += $tempAttach
$counter++
}
$body += "</p>"
#Mail info
$eMail.from = $emailFrom
$eMail.To.add($sendto)
$eMail.Subject = $emailSubject
$eMail.Body = $body
$eMail.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.Send($eMail)
#Dispose attachments
foreach ($tempAttach in $attachArray) {
$tempAttach.dispose()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment