在Django邮件中嵌入HTML图片失败,寻求解决方法
Django HTML邮件内嵌图片无法显示的解决方案
你问题的核心是直接用本地文件路径作为图片src,邮件客户端无权访问服务器/本地文件系统,必须把图片作为邮件内嵌附件,通过CID(Content-ID)引用。以下是具体修复方案:
1. 修改视图代码
需将图片添加为内嵌附件,并生成对应CID供模板调用:
import os from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags # 正确拼接路径(用正斜杠或双反斜杠避免转义问题) img_path = os.path.join(settings.BASE_DIR, 'Mods/Surveys/static/images/Survey.jpg') html_content = render_to_string('email_template.html', { 'survey': survey, 'url': survey.url, }) msg = EmailMultiAlternatives( subject=survey.subject, body=strip_tags(html_content), from_email='my email', to=[respondant.email] ) msg.attach_alternative(html_content, "text/html") # 嵌入图片并设置Content-ID with open(img_path, 'rb') as img_file: msg.attach( 'Survey.jpg', img_file.read(), 'image/jpeg', headers={'Content-ID': '<survey_image>'} # CID需用尖括号包裹 ) msg.send()
2. 修改模板代码
将图片src改为引用对应CID:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <h1>{{ survey.subject}}</h1> <p>{{ survey.body}}</p> <a href="{{ url }}"><img src="cid:survey_image" alt="Survey Image"></a> </body> </html>
关键说明
- CID作用:作为内嵌资源的唯一标识,让邮件客户端关联附件与HTML中的引用,避免图片被当作普通附件或加载失败。
- 路径规范:Windows系统下用正斜杠
/或双反斜杠\\,防止单斜杠引发转义错误。 - MIME类型:根据图片格式设置,JPG用
image/jpeg,PNG用image/png。
内容的提问来源于stack exchange,提问作者Emanuel Ticona
相关产品推荐
相关产品推荐

