Graph and PowerShell Blog | About | Links
Using Graph to send emails with inline image
02-Mar-23

There are a number of excellent articles on sending authenticated mail via MS Graph, replacing SMTP relay. Unfortunately, none of them addressed adding inline images as attachments. This can be useful if you need to ensure the images are displayed correctly and don't have a website to host the images.

$ConnectParams = @{
ClientId = 'xxxxx'
TenantId = 'xxxxx'
CertificateThumbprint = 'xxxxx'
}
Connect-Graph @ConnectParams

Function ConvertTo-IMicrosoftGraphRecipient {
[cmdletbinding()]
Param(
[array]$smtpAddresses
)
foreach ($address in $smtpAddresses) {
@{
emailAddress = @{address = $address}
}
}
}

Function ConvertTo-IMicrosoftGraphAttachment {
[cmdletbinding()]
Param(
[string[]]$UploadDirectory
)
foreach ($fl in $UploadDirectory) {
if ($fl) { }
else { $fl = "un" }
$fpath = "C:\inetpub\wwwroot\flags\PNG\$fl.png"
$encodedAttachment = [convert]::ToBase64String((Get-Content $fpath -Encoding byte))
@{
"@odata.type"= "#microsoft.graph.fileAttachment"
name = $fl
contentBytes = $encodedAttachment
contentID = $fl
contentType = "image/png"
}
}
}

$arFlags = @()
foreach ($lc in $logCollection)
{
$f_flag = $lc.flag

if ($f_flag -eq "") { $f_flag = "un" }
write-host "flag $f_flag"
if ($flaglist -notcontains $f_flag) { $arFlags += $f_flag }

$null = $flaglist.add("$f_flag")
}
$arflags

$attachments = ConvertTo-IMicrosoftGraphAttachment -UploadDirectory $arflags

$emailRecipients = @(
'user@domain.com'
)

$toRecipients = ConvertTo-IMicrosoftGraphRecipient -SmtpAddresses $emailRecipients

$addimg = "cid" + ":" + "ie"

$contentMG += "<table><th>Flag></th></tr>"
foreach ($lc in $logCollection)
{
$l_flag = $lc.flag
$l_location = $lc.location
$contentMG += "<tr><td><img src=cid`:$l_flag></td></tr>"
}

$body = @{
content = $contentMG
ContentType = 'html'
}

#Create Message (goes to drafts)
$Message = New-MgUserMessage -UserId user@domain.com -Body $body -ToRecipients $toRecipients -Subject "Subject" -Attachments $Attachments

#Send Message
Send-MgUserMessage -UserId user@domain.com -MessageId $Message.Id