You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django应用中发送含内嵌图片的HTML邮件?

在Django中发送内嵌图片的HTML邮件(解决{% load static %}无效问题)

{% load static %}生成的是相对路径或本地路径,邮件客户端无法识别这些路径,所以没法加载图片。下面是两种可行的解决方法:

方法一:用CID内嵌图片(推荐,图片随邮件发送,无需外部访问)

这是邮件内嵌图片的标准方案,通过给图片分配唯一的Content-ID(CID),在HTML里引用这个CID即可。

1. 视图层代码(发送邮件逻辑)

from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.conf import settings
import os

def send_logo_email(to_email):
    # 读取本地静态文件里的图片
    logo_path = os.path.join(settings.STATIC_ROOT, "images", "company_logo.png")
    with open(logo_path, "rb") as logo_file:
        logo_data = logo_file.read()

    # 渲染HTML邮件模板
    html_template = render_to_string("emails/welcome.html")

    # 创建邮件对象
    email = EmailMultiAlternatives(
        subject="欢迎加入我们",
        body="请查看HTML版本邮件获取完整内容",
        from_email=settings.DEFAULT_FROM_EMAIL,
        to=[to_email]
    )
    email.attach_alternative(html_template, "text/html")

    # 添加内嵌图片,设置Content-ID
    email.attach(
        "company_logo.png",
        logo_data,
        "image/png",
        headers={"Content-ID": "<company_logo>"}  # CID必须用尖括号包裹
    )

    # 发送邮件
    email.send()

2. HTML邮件模板(emails/welcome.html)

不需要用{% load static %},直接通过CID引用图片:

<!DOCTYPE html>
<html>
<body>
    <div style="text-align: center;">
        <img src="cid:company_logo" alt="公司Logo" width="150">
        <h2>欢迎成为我们的用户!</h2>
        <p>感谢您的注册,期待为您服务。</p>
    </div>
</body>
</html>

方法二:使用绝对URL(适合图片可公开访问的场景)

如果你的静态文件托管在CDN或者服务器可以公开访问,直接用绝对URL引用图片即可:

1. 配置绝对STATIC_URL(可选)

在settings.py里设置绝对路径:

STATIC_URL = "https://your-domain.com/static/"

2. 模板里引用绝对URL

如果视图传递了request对象,可以用它生成完整URL:

{% load static %}
<!DOCTYPE html>
<html>
<body>
    <img src="{{ request.build_absolute_uri }}{% static 'images/company_logo.png' %}" alt="公司Logo">
    <p>欢迎邮件内容...</p>
</body>
</html>

如果没有request对象,直接写完整绝对路径:

<img src="https://your-domain.com/static/images/company_logo.png" alt="公司Logo">

关键说明

  • {% load static %}本身没问题,但它生成的是相对路径,邮件客户端不知道这个路径对应的服务器地址,所以无法加载图片。
  • 内嵌图片(CID方式)不需要收件人有网络就能看到图片,体验更好;绝对URL方式依赖外部访问,适合图片需要经常更新的场景。

内容的提问来源于stack exchange,提问作者VINCENTIUS SELLO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 17:15:01