Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Embedded Image in Email Body using Microsoft Graph or Outlook REST API

When we get email using Microsoft Graph/Outlook REST API it's body contains the references for embedded images like below.

<img src="cid:[email protected]">

I am looking to find out a way so i can display the embedded images properly as the above image tag does not display any image. I have done some search but did not found any help on that.

Below is sample code for getting an email by id using Microsoft Graph API.

// Get the message.
Message message = await graphClient.Me.Messages[id].Request(requestOptions).WithUserAccount(ClaimsPrincipal.Current.ToGraphUserAccount()).GetAsync();
like image 649
Glen Souza Avatar asked Jun 15 '18 16:06

Glen Souza


People also ask

Is Microsoft Graph A REST API?

Microsoft Graph is a RESTful web API that enables you to access Microsoft Cloud service resources.

What is Microsoft Graph mail?

Microsoft Graph lets your app get authorized access to a user's Outlook mail data in a personal or organization account. With the appropriate delegated or application mail permissions, your app can access the mail data of the signed-in user or any user in a tenant.

Is Microsoft Graph an API gateway?

Microsoft Graph is the unified gateway for developers to access all the data, intelligence and APIs housed in Microsoft's intelligent cloud including Exchange, SharePoint, Azure Active Directory, OneDrive, Outlook, OneNote, Planner, Excel and more.


1 Answers

For getting attached resources with email using Microsoft Graph API you need to get email like below.

// Get the message with all attachments(Embedded or separately attached).
Message message = await graphClient.Me.Messages[id].Request(requestOptions).WithUserAccount(ClaimsPrincipal.Current.ToGraphUserAccount()).Expand("attachments").GetAsync();

Once you have all attachments with email detail you need to iterate through attachments list and check if attachment IsInline property is set as true then simply replace the

cid:[email protected]

with Base64String created from bytes array of attachment.

string emailBody = message.Body.Content;
foreach (var attachment in message.Attachments)
{
   if (attachment.IsInline.HasValue && attachment.IsInline.Value)
   {
     if ((attachment is FileAttachment) &&(attachment.ContentType.Contains("image")))
     {
        FileAttachment fileAttachment = attachment as FileAttachment;
        byte[] contentBytes = fileAttachment.ContentBytes;
        string imageContentIDToReplace = "cid:" + fileAttachment.ContentId;
        emailBody = emailBody.Replace(imageContentIDToReplace, 
        String.Format("data:image;base64,{0}", Convert.ToBase64String(contentBytes as 
        byte[])));
     }

  }
}

Now render the email body using emailBody variable it will display all embedded images.

like image 170
Asad Avatar answered Sep 24 '22 03:09

Asad