使用C#发送含内嵌图片邮件:部分收件人无法查看图片问题
解决C#发送内嵌图片邮件部分收件人无法查看的问题
我之前也踩过一模一样的内嵌图片显示不一致的坑,大概率是你没有正确将图片标记为内嵌资源(LinkedResource),而是误当成普通附件处理了——这就是为什么部分邮件客户端能识别,部分不行的核心原因。
问题根源
你HTML里用了cid:#IMG01#这种格式,但代码里只提到了添加PDF附件,完全没处理内嵌图片的关联逻辑:
- 普通
Attachment是作为独立附件存在的,邮件客户端只会把它当成附件展示,不会内嵌到HTML里 - 内嵌图片必须用
LinkedResource类,并且要让HTML里的cid和LinkedResource的ContentId完全匹配,还要注意cid的格式规范
修正后的完整代码示例
先把你的HTML里的cid改成规范格式(避免#这类特殊字符,推荐用[唯一标识]@[自定义域名]的格式):
<IMG SRC="cid:image01@myapp.com" > <IMG SRC="cid:image02@myapp.com" >
然后修改C#代码,正确关联内嵌图片:
var message = new MailMessage { Priority = MailPriority.Normal, Sender = new MailAddress(utente.Email, "xxx.it"), From = new MailAddress(utente.Email, "xxx.it") }; message.To.Add(new MailAddress("xxx@tiscali.it", "aaaaaaaa")); message.Subject = "xywz"; // 用AlternateView处理HTML内容和内嵌资源,兼容性更好 string htmlBody = Modello; // 这里是你修改后的HTML内容 AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html); // 添加第一张内嵌图片 LinkedResource img1 = new LinkedResource(Path.Combine(path, "image1.png"), MediaTypeNames.Image.Png); img1.ContentId = "image01@myapp.com"; // 必须和HTML里的cid完全一致 img1.ContentDisposition.Inline = true; // 明确标记为内嵌资源 htmlView.LinkedResources.Add(img1); // 添加第二张内嵌图片 LinkedResource img2 = new LinkedResource(Path.Combine(path, "image2.jpg"), MediaTypeNames.Image.Jpeg); img2.ContentId = "image02@myapp.com"; img2.ContentDisposition.Inline = true; htmlView.LinkedResources.Add(img2); // 将AlternateView添加到邮件 message.AlternateViews.Add(htmlView); // 添加普通PDF附件 Attachment AttPrinc = new Attachment(Path.Combine(path, "Attachment.pdf")); message.Attachments.Add(AttPrinc);
关键注意事项
- ContentId格式要规范:不要用#、空格这类特殊字符,用
xxx@xxx.com这种格式,很多邮件客户端(比如Outlook、部分企业web邮箱)对cid格式有严格要求,不符合的会直接忽略 - 必须用LinkedResource:别把内嵌图片当成普通Attachment添加,否则部分客户端会把它显示成附件,而不是内嵌在HTML里
- 明确标记Inline:设置
ContentDisposition.Inline = true,强制告诉邮件客户端这是内嵌资源 - 多客户端测试:有些web邮箱会默认屏蔽内嵌图片,需要用户手动允许显示,但只要你的配置正确,用户允许后就能正常看到
验证方法
发送测试邮件给自己,查看邮件源码,确认:
- 存在
Content-ID: <image01@myapp.com>的头部 - 对应的资源
Content-Disposition是inline而不是attachment
内容的提问来源于stack exchange,提问作者Giorgio Forti
相关产品推荐
相关产品推荐

