July 2, 2020

Embedded images that appear in Gmail using Microsoft Graph

Embedded images that appear in Gmail using Microsoft Graph

We just finished dealing with some new regulatory requirements (Regulation Best Interest and Form CRS, if you're curious). Among other things, we now send an automated email (containing a link to Form CRS) when someone opens a new account.

This email contains an embedded (or inline) image using CID. I noticed that the embedded image was not displaying in Gmail, but it was displaying in the other email clients I tested just fine. The problem? I didn't specify the Content-ID header for the attachment.

The email is sent using an Azure Function (written in C#) which uses Microsoft Graph to connect to Office 365.

Image in Email:

<p>
    <img src="cid:email-img.png">
</p>

Azure Function:

I'm using a Graph client instance to send an email with an attachment, the attachment being the image I want to appear inline. The key part here is that you specify the ContentId property in the FileAttachment object, which ends up as the Content-ID header. It should match the attachment name.

Before I added this, the inline image was not appearing in Gmail clients.

Attachments = new MessageAttachmentsCollectionPage()
{
    new FileAttachment
    {
        Name = "email-img.png",
        ContentType = "image/png",
        ContentBytes = attachmentBytes,
        ContentId = "email-img.png" // don't forget this part
    }
}

It took me a little bit of time and research to figure this out as I'm still pretty "green" with Microsoft Graph, but maybe this post will save someone else a little time down the road!