You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# WebBrowser中显示Microsoft.Graph.Models.Message的图片?

解决方案:修复WebBrowser展示邮件时内嵌图片不显示问题

问题核心是邮件HTML中的内嵌图片使用cid:协议引用附件,但直接加载HTML文本时,WebBrowser无法解析这些cid对应的本地附件,需要手动将cid替换为本地文件的绝对路径(file协议格式)。

具体修改步骤

  • 加载MimeMessage后,遍历所有附件,建立CID值与本地文件路径的映射表
  • 将HTML内容中的cid:xxx替换为file:///本地文件绝对路径
  • 确保替换后的路径使用正确的URI格式(比如Windows路径要转成file:///C:/temp/xxx.png)

修改后的完整代码

private async void MostrarMensajeEnWebBrowser(Message message)
{
    emailWebBrowser.ScriptErrorsSuppressed = true;
    var gservice = new GraphService();
    var imapClient = new ImapMail(gservice);
    string tempFolder = Path.GetTempPath();

    if (message.HasAttachments)
    {                
        await imapClient.SaveAttachmentMail(message, tempFolder); // 下载所有附件到临时文件夹
    }
    // 修正原代码笔误:"mensaje"应为"message"
    await imapClient.SaveMail(message, tempFolder);
    string pathEML = Path.Combine(tempFolder, message.Subject.Replace(":", "_").Replace("/", "_") + ".eml");
    MimeMessage msg = MimeMessage.Load(pathEML);
    string bodyHTML = msg.HtmlBody ?? msg.TextBody;

    // 处理内嵌图片的CID引用
    if (msg.Attachments.Any())
    {
        var cidToPathMap = new Dictionary<string, string>();
        foreach (var attachment in msg.Attachments)
        {
            // 只处理内嵌类型的附件(ContentDisposition为Inline)
            if (attachment is MimePart part && part.ContentDisposition?.Disposition == ContentDisposition.Inline)
            {
                // 获取附件的CID值(去除首尾尖括号)
                string cid = part.ContentId?.Trim('<', '>');
                if (!string.IsNullOrEmpty(cid))
                {
                    // 拼接本地附件路径(需确保SaveAttachmentMail保存的文件名与attachment.FileName一致)
                    string attachmentPath = Path.Combine(tempFolder, attachment.FileName);
                    // 转换为file协议的URI格式
                    string fileUri = new Uri(attachmentPath).AbsoluteUri;
                    cidToPathMap[cid] = fileUri;
                }
            }
        }

        // 替换HTML中的cid引用
        foreach (var kvp in cidToPathMap)
        {
            bodyHTML = bodyHTML.Replace($"cid:{kvp.Key}", kvp.Value);
        }
    }

    emailWebBrowser.DocumentText = bodyHTML;
}

关键细节说明

  1. CID匹配逻辑:邮件内嵌附件的ContentId通常带尖括号(比如<image123@example.com>),需要去掉尖括号后再匹配HTML中的cid:image123@example.com。
  2. 文件URI格式:必须用file:///开头(三个斜杠),Windows本地路径转成URI格式可避免反斜杠导致的解析错误。
  3. 附件路径验证:如果SaveAttachmentMail保存时修改了附件文件名,需调整映射路径的拼接逻辑,确保指向正确的本地文件。

内容的提问来源于stack exchange,提问作者Pablo Otero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 02:51:20