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

时间:2018-06-15 16:35:16

标签: asp.net-mvc email outlook office365 microsoft-graph

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

<img src="cid:image001.jpg@1D3E60C.5A00BC30">

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

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

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

2 个答案:

答案 0 :(得分:2)

要使用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();

一旦所有带有电子邮件详细信息的附件都需要遍历附件列表,并检查附件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[])));
     }

  }
}

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

答案 1 :(得分:0)

使用以下代码在 C# 中使用图形 Api 在图像标签上显示徽标图像。

var fileAttachment = new FileAttachment
            {
                ODataType = "#microsoft.graph.fileAttachment",
                Name = Path.GetFileName(attachment),
                ContentLocation = attachment,
                ContentBytes = contentBytes,
                ContentType = contentType,
                ContentId= contentId,
                IsInline = true
            };

注意:这里IsInline = true如果您只想在图像标签上显示图像而不是作为附件显示,则必须添加IsInline = true