使用 Microsoft Graph 或 Outlook REST API 在电子邮件正文中呈现嵌入的图像

Gle*_*uza 4 email asp.net-mvc outlook office365 microsoft-graph-api

当我们使用 Microsoft Graph/Outlook REST API 收到电子邮件时,它的正文包含对嵌入图像的引用,如下所示。

<img src="cid:image001.jpg@1D3E60C.5A00BC30">
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种方法,以便我可以正确显示嵌入的图像,因为上面的图像标签不显示任何图像。我做了一些搜索,但没有找到任何帮助。

以下是使用 Microsoft Graph API 通过 id 获取电子邮件的示例代码。

// Get the message.
Message message = await graphClient.Me.Messages[id].Request(requestOptions).WithUserAccount(ClaimsPrincipal.Current.ToGraphUserAccount()).GetAsync();
Run Code Online (Sandbox Code Playgroud)

Asa*_*sad 7

要使用 Microsoft Graph API 通过电子邮件获取附加资源,您需要收到如下电子邮件。

// 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();
Run Code Online (Sandbox Code Playgroud)

一旦您拥有带有电子邮件详细信息的所有附件,您需要遍历附件列表并检查附件 IsInline 属性是否设置为 true,然后只需替换

cid:image001.jpg@1D3E60C.5A00BC30

使用从附件的字节数组创建的 Base64String。

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[])));
     }

  }
}
Run Code Online (Sandbox Code Playgroud)

现在使用 emailBody 变量渲染电子邮件正文,它将显示所有嵌入的图像。