Django项目发送带PDF附件邮件报错:expected bytes-like object, not HttpResponse
问题解决:Django发送PDF附件时出现TypeError错误
错误原因
你的render_to_pdf函数返回的是HttpResponse对象,但EmailMultiAlternatives.attach()方法需要的是字节类型的PDF内容,而非HttpResponse对象,这直接导致了expected bytes-like object, not HttpResponse的错误。
修改步骤
1. 修正utils.py中的render_to_pdf函数
将返回HttpResponse改为直接返回PDF的字节数据,使其适配邮件附件的要求:
from io import BytesIO from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: # 返回PDF字节内容,而非HttpResponse对象 return result.getvalue() return None
2. 调整views.py中的sendMail函数
增加PDF生成结果的校验,确保附件内容有效后再发送邮件:
from django.core.mail import EmailMultiAlternatives from django.shortcuts import render from .utils import render_to_pdf def sendMail(request): # 替换为你实际的上下文数据 context = {} pdf_content = render_to_pdf('cart/commande.html', context) if not pdf_content: # 处理PDF生成失败的场景 return render(request, 'cart/error.html') subject, from_email, to = '带PDF附件的邮件:编号N°0001', 'aab@gmail.com', 'too@gmail.com' text_content = '你好,这是一封带有PDF附件的邮件' html_content = '<p>你好,这是一封带有PDF附件的邮件。</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") # 附件参数:文件名、字节内容、MIME类型 msg.attach('commande.pdf', pdf_content, 'application/pdf') msg.send() return render(request, 'cart/succes.html')
关键说明
render_to_pdf现在直接返回PDF字节流,完全符合msg.attach()的参数要求- 新增PDF生成失败的判断逻辑,避免无效内容触发后续报错
- 附件文件名添加
.pdf后缀,方便收件人识别文件类型
内容的提问来源于stack exchange,提问作者Pathia Nanto
相关产品推荐
相关产品推荐

