【问题标题】:Images in Django email template not loading in emailDjango电子邮件模板中的图像未加载到电子邮件中
【发布时间】:2021-04-25 17:38:44
【问题描述】:

我正在使用模板通过 Django 发送电子邮件。电子邮件已发送,但图像未显示。

在模板 html 文件中,我有:

{% load static %}

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

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

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")
)

我的图像在静态文件夹中的一个名为 images 的文件夹中。

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

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

    试试这个

    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)
    

    【讨论】:

    猜你喜欢
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2012-12-26
    • 2015-05-29
    • 2015-10-08
    • 1970-01-01
    相关资源
    最近更新 更多