How to embed Image inline in Email Body using Microsoft Graph
Asked Answered
S

2

8

I am using a Function app to trigger a mail, using MS Graph API, the mail body text is getting triggered properly but facing issue in rendering the header and footer image shown in picture. How to solve this issue in the body level.

enter image description here

Below are the references of the above images in HTML/Blob file

  <img src=cid:Header.jpg>
    <img src=cid:footer.png>
    <ContentIDs>Header.jpg, footer.png</ContentIDs>

Code used in rendering the body.

             var mailContent = new Message
                {
                    Subject = em.Subject,
                    Body = new ItemBody
                    {
                        ContentType = BodyType.Html,
                        Content = m.Body,
                        ODataType = null
                    },
                    ToRecipients = toEmails,
                    CcRecipients = ccEmails,
                    ODataType = null
                };    

EDIT: Currently facing bad request in Function App after this changes. I am trying to resolve that. If you see any discrepancy in this below code feel free to comment.

            var imagePath = @"<path\Header.jpg>";
            var imageID = "Header.jpg";//file name
            byte[] imageArray = System.IO.File.ReadAllBytes(imagePath);
            var imagePath2 = @"<path\footer.png">;
            var imageID2 = "footer.png";
            byte[] imageArray2 =System.IO.File.ReadAllBytes(imagePath2);

            
            var mContent = new Message
            {
                Subject = t.Subject,//parsing from the template
                Body = new ItemBody
                {
                    ContentType = BodyType.Html,
                    Content = m.Body,
                    ODataType = "#microsoft.graph.fileAttachment"
                },
                ToRecipients = toEmails,
                CcRecipients = ccEmails,
                ODataType = "#microsoft.graph.fileAttachment",
                HasAttachments = true,
                Attachments = new MessageAttachmentsCollectionPage()
                    {
                            new FileAttachment
                        {
                                
                                ContentBytes= imageArray,
                                ContentType = "image/jpeg",
                                ContentId= imageID,
                                IsInline=true,
                                Name = "theHead",
                               
                        },
                            new FileAttachment
                            {
                                
                                ContentBytes= imageArray2,
                                ContentType = "image/png",
                                ContentId= imageID2,
                                IsInline=true,
                                Name = "thefoot",
                            }
                    }
            };
Sexagenary answered 1/6, 2021 at 12:10 Comment(8)
How's going? Has your issue got resolvced?Dochandorrach
Hi @StanleyGong Thanks a lot for answering it. I have took some code from your reference, but currently I am facing bad request in Function App.Sexagenary
I am not sure if it is the point, but seems there lost a = at the 4th line of your codeDochandorrach
Sorry messed that up during editing , added it back.Sexagenary
I have tested your code at my side, after removing 2 lines ODataType = "#microsoft.graph.fileAttachment" , your code works for meDochandorrach
@StanleyGong yeah you were right I kept them as null it worked. We can close it. Thanks a lot once again.Sexagenary
Glad to know my post is helpful. Please click on the check mark beside the answer to toggle it from greyed out to filled in to accept it as an answer, it will help others and close this question : )Dochandorrach
It helped here but for java is not helping :) Removing that "#microsoft.graph.fileAttachment" is causing my call to fail.Gravamen
D
9

I write a demo for you , try the simple console app below:

using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;

namespace sendEmails
{
    class Program
    {
        static void Main(string[] args)
        {
            var appID = "";
            var appSec = "";
            var tenantID = "";
            

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                .Create(appID)
                .WithTenantId(tenantID)
                .WithClientSecret(appSec)
                .Build();

            ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);

            GraphServiceClient graphServiceClient = new GraphServiceClient(authenticationProvider);

            var imagePath = @"<your image path>";
            var imageID = "image1";
            

            byte[] imageArray = System.IO.File.ReadAllBytes(imagePath);

            var body = "<h1>this is superman </br> <img src='cid:"+ imageID + "'/></h1>";
            var attachments = new MessageAttachmentsCollectionPage()
            {
                new FileAttachment{
                    ContentType= "image/jpeg",
                    ContentBytes = imageArray,
                    ContentId = imageID,
                    Name= "test-image"
                }
            };
            
            var message = new Message
            {
                Subject = "TEST SENDING IMAGE ",
                Body = new ItemBody
                {
                    ContentType = BodyType.Html,
                    Content = body,
                    ODataType = null
                },
                ToRecipients = new List<Recipient>()
                {
                    new Recipient
                    {
                        EmailAddress = new EmailAddress
                        {
                            Address = "<receiver email>"
                        }
                    }
                },
                Attachments = attachments

            };
            
            graphServiceClient.Users["<user upn>"].SendMail(message, false).Request().PostAsync().GetAwaiter().GetResult();
            Console.WriteLine("ok");
        }
    }
}

Result :

enter image description here

Dochandorrach answered 2/6, 2021 at 4:17 Comment(0)
C
3

Here is another easy way to embed images into email messages sent using Microsoft Graph, good specially for small images such as logos.

First, go to one of the free sites that convert your files to base64 (e.g. here). Then, use the encoded image string as src for your <img> tag in the message body.

const string image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAGNCAMAAAAIKde7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR ...";

Message message = new()
{
    ...,
    Body = new ItemBody
    {
        ContentType = BodyType.Html,
        Content = $@"<img width=500 height=500 alt=""Your alt text"" src=""{image}"">"
        }
    }
}

This way, you won't have to mess with attachments.

Chimera answered 26/9, 2023 at 14:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.