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

如何在Django的send_mail()方法中发送HTML页面?

在Django中使用send_mail()发送HTML格式邮件(基于Jinja模板)

要通过send_mail()发送HTML邮件,核心是利用它的html_message参数,结合Jinja模板渲染出HTML内容即可,具体步骤如下:

1. 创建HTML邮件模板

在你的Django项目模板目录下(比如templates/emails/)新建一个HTML模板文件,比如order_notification.html,写入带Jinja语法的HTML内容:

<!DOCTYPE html>
<html>
<head>
    <title>订单通知</title>
</head>
<body>
    <h3>您好,{{ username }}!</h3>
    <p>您的订单 <strong>{{ order_id }}</strong> 已成功处理,预计3个工作日内送达。</p>
    <p>如有疑问,请联系客服:support@example.com</p>
</body>
</html>

2. 渲染模板并发送邮件

在视图或任务函数中,使用render_to_string渲染模板,再传入send_mail()的html_message参数:

from django.core.mail import send_mail
from django.template.loader import render_to_string

def send_order_notification(user_email, username, order_id):
    # 准备模板上下文数据
    context = {
        'username': username,
        'order_id': order_id
    }

    # 渲染HTML模板为字符串
    html_content = render_to_string('emails/order_notification.html', context)

    # 纯文本版本(兼容不支持HTML的邮件客户端)
    plain_content = f"您好,{username}!您的订单{order_id}已成功处理,预计3个工作日内送达。如有疑问,请联系客服:support@example.com"

    # 调用send_mail发送
    send_mail(
        subject='您的订单已处理完成',
        message=plain_content,  # 必填的纯文本内容
        from_email='noreply@example.com',
        recipient_list=[user_email],
        html_message=html_content  # HTML格式内容
    )

关键说明

  • html_message是Django 1.7及以上版本支持的参数,专门用于传递HTML邮件内容
  • 必须提供message参数(纯文本版本),这是为了兼容那些不支持HTML渲染的邮件客户端,确保用户能看到基础内容
  • 模板中可以正常使用Jinja2的所有语法,比如变量、循环、过滤器等

调试技巧

如果想测试邮件内容而不实际发送,可以在settings.py中配置控制台后端:

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

这样邮件内容会直接打印在控制台,方便你检查HTML渲染是否正确。

内容的提问来源于stack exchange,提问作者almost there

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:35:11