Mailkit使用LinkedResources.Add加载内嵌资源图片的问题咨询
LinkedResources.Add 仅支持本地文件路径作为入参,无法识别WPF专属的pack协议资源路径,你可以先将内嵌资源读取为流/字节数组,调用方法的对应重载实现嵌入。
前置检查
首先确认图片资源的「生成操作」属性配置正确:
- 若使用WPF pack URI读取:生成操作设为 资源
- 若使用通用程序集读取:生成操作设为 嵌入的资源
方案1:WPF项目pack URI读取方案
var builder = new BodyBuilder(); // 读取pack URI对应的资源流 Uri imageUri = new Uri("pack://application:,,,/Resources/LOGO_275.png", UriKind.Absolute); StreamResourceInfo streamInfo = Application.GetResourceStream(imageUri); if (streamInfo == null) { throw new FileNotFoundException("未找到指定的内嵌图片资源"); } // 将资源流转为字节数组,避免流生命周期问题 byte[] imageBytes; using (Stream stream = streamInfo.Stream) using (var ms = new MemoryStream()) { stream.CopyTo(ms); imageBytes = ms.ToArray(); } // 调用字节数组重载添加内嵌资源 var image = builder.LinkedResources.Add("LOGO_275.png", imageBytes); image.ContentId = MimeUtils.GenerateMessageId();
方案2:通用程序集读取方案(无WPF依赖,兼容所有.NET项目)
var builder = new BodyBuilder(); // 获取当前程序集,若资源在其他程序集请替换为对应程序集的获取逻辑 var assembly = Assembly.GetExecutingAssembly(); // 资源路径格式为 {程序集默认命名空间}.{文件夹层级}.{完整文件名},例如项目默认命名空间为MyApp,图片在Resources文件夹下,路径为MyApp.Resources.LOGO_275.png string resourcePath = "MyApp.Resources.LOGO_275.png"; using (Stream stream = assembly.GetManifestResourceStream(resourcePath)) { if (stream == null) { throw new FileNotFoundException("未找到指定的内嵌图片资源", resourcePath); } // 调用流重载添加内嵌资源 var image = builder.LinkedResources.Add("LOGO_275.png", stream); image.ContentId = MimeUtils.GenerateMessageId(); }
正文引用资源
如果使用HTML格式的邮件正文,通过cid:前缀关联ContentId即可展示图片:
builder.HtmlBody = $"<div>测试正文<img src=\"cid:{image.ContentId}\" alt=\"logo\" /></div>";
内容的提问来源于stack exchange,提问作者Mowag
相关产品推荐
相关产品推荐

