使用Django send_mass_mail发送HTML批量邮件时触发ValueError报错
解决Django批量发送HTML邮件时的ValueError问题
错误原因
你使用的send_mass_mail函数要求每个消息元组必须是4个元素:(subject, plain_text_message, from_email, recipient_list),但你在message1和message2里额外添加了第5个参数html_message,导致函数内部解包时触发ValueError: too many values to unpack (expected 2)(实际是预期4个值,你传入了5个)。另外,send_mass_mail默认只支持纯文本邮件,无法直接传入HTML内容。
正确实现方式
要批量发送HTML格式邮件,应该使用EmailMultiAlternatives类(支持同时包含纯文本和HTML版本),配合邮件连接批量发送,代码示例如下:
from django.core.mail import EmailMultiAlternatives, get_connection from django.template.loader import render_to_string from django.utils.html import strip_tags from rest_framework.views import APIView from rest_framework.response import Response class SendMailViews(APIView): def post(self, request, format=None): # 渲染HTML邮件模板 html_message = render_to_string('email/test.html') # 生成纯文本版本(作为降级方案) plain_message = strip_tags(html_message) from_email = 'rahulsha24445@gmail.com' # 准备批量邮件列表 email_list = [] # 构建第一封邮件 msg1 = EmailMultiAlternatives( subject="subject", body=plain_message, from_email=from_email, to=['sharmaviraj300@gmail.com'] ) # 绑定HTML内容 msg1.attach_alternative(html_message, "text/html") email_list.append(msg1) # 构建第二封邮件 msg2 = EmailMultiAlternatives( subject="subject", body=plain_message, from_email=from_email, to=['abhijeetlaal7899@gmail.com'] ) msg2.attach_alternative(html_message, "text/html") email_list.append(msg2) # 批量发送邮件(复用连接提升效率) with get_connection() as connection: connection.send_messages(email_list) return Response({"status": True})
简化优化(针对多收件人场景)
如果收件人数量较多,可以用循环批量构建邮件对象,避免重复代码:
# 定义所有收件人 recipients = ['sharmaviraj300@gmail.com', 'abhijeetlaal7899@gmail.com'] email_list = [] for to_email in recipients: msg = EmailMultiAlternatives( subject="subject", body=plain_message, from_email=from_email, to=[to_email] ) msg.attach_alternative(html_message, "text/html") email_list.append(msg)
关键说明
EmailMultiAlternatives:专门用于发送同时包含纯文本和HTML的邮件,确保不支持HTML的邮箱能正常显示纯文本内容。get_connection():获取邮件连接,通过send_messages批量发送,减少多次建立连接的开销,提升发送效率。
内容的提问来源于stack exchange,提问作者dev_abhi
相关产品推荐
相关产品推荐

