首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Django电子邮件模板中没有在电子邮件中加载的图像

Django电子邮件模板中没有在电子邮件中加载的图像
EN

Stack Overflow用户
提问于 2021-04-25 17:38:44
回答 2查看 1.7K关注 0票数 1

我使用一个模板使用Django发送电子邮件。电子邮件被发送,但图像不显示。

在模板html文件中,我有:

代码语言:javascript
运行
复制
{% load static %}

<img class="margin-bottom" height="52px" width="140px" src="{% static 'images/image.png' %}" />

在settings.py文件中,我有以下内容:

代码语言:javascript
运行
复制
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]

STATIC_URL = env('STATIC_URL', cast=str, default='/static/')

STATIC_ROOT = env(
    'STATIC_ROOT', cast=str, default=os.path.join(BASE_DIR, "collected_static")
)

我把我的图像放在一个叫做静态文件夹的文件夹中。

EN

Stack Overflow用户

回答已采纳

发布于 2021-04-25 18:50:38

您必须使用MultiPart和cid:。发送带有图像的html邮件几乎总是一个坏主意。它将垃圾邮件指向您的邮件和smtp服务器。

尝尝这个

代码语言:javascript
运行
复制
from email.mime.image import MIMEImage
from django.core.mail import EmailMultiAlternatives

subject = 'Django sending email'
body_html = '''
<html>
    <body>
        <img src="cid:logo.png" />
        <img src="https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif" />
    </body>
</html>
'''

from_email = 'hello@localhost.com'
to_email = 'hi@localhost.com'

msg = EmailMultiAlternatives(
    subject,
    body_html,
    from_email=from_email,
    to=[to_email]
)

msg.mixed_subtype = 'related'
msg.attach_alternative(body_html, "text/html")
img_dir = 'static'
image = 'logo.png
file_path = os.path.join(img_dir, image)
with open(file_path, 'r') as f:
    img = MIMEImage(f.read())
    img.add_header('Content-ID', '<{name}>'.format(name=image))
    img.add_header('Content-Disposition', 'inline', filename=image)
msg.attach(img)
票数 3
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67256407

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档