You need to enable JavaScript to run this app. Django同视图生成PDF后作Gmail附件发送TypeError问题解决
优惠活动
大模型
产品
解决方案
定价
更多

Django同视图生成PDF后作Gmail附件发送TypeError问题解决

报错根因

调用email.attach_file(pdf)时触发类型错误,本质是:

  • attach_file() 是Django邮件封装提供的方法,入参必须是本地磁盘上的文件路径(支持字符串、字节、os.PathLike格式),方法内部会自行读取路径对应的文件内容作为附件
  • 你传入的pdf是render_to_pdf()返回的HttpResponse对象——这个对象是用来给前端返回HTTP响应的容器,既不是文件路径,也无法被attach_file()识别为附件内容,因此直接抛出类型不匹配的错误。
修复步骤

1. 解耦PDF生成逻辑与HTTP响应

原render_to_pdf()函数为了直接给前端返回PDF下载响应,将生成的PDF字节包装进了HttpResponse对象。调整函数实现,让它直接返回内存中生成的原始PDF字节流,需要返回前端时再自行包装为HttpResponse即可。

调整后的utils.py代码:

from io import BytesIO
from django.template.loader import get_template
import pisa

def render_to_pdf(template_src, context_dict=None):
    # 修复Python可变默认参数的隐患,避免多次调用时context残留旧值
    if context_dict is None:
        context_dict = {}
    template = get_template(template_src)
    html = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
    if pdf.err:
        return None
    # 直接返回PDF原始字节,不再绑定HttpResponse
    return result.getvalue()

2. 调整视图中的邮件附件逻辑

内存中生成的PDF不需要落地为磁盘文件,应使用邮件模块提供的attach()方法直接附加字节内容,而非使用依赖本地文件路径的attach_file()方法。

调整后的views.py代码:

def submit_report(request, pk):
    Industry_obj = Industry.objects.get(id=pk)
    Industry_Report_obj = Industry_obj.industry_report_set.all()
    report_tableA_obj = report_tableA.objects.filter(industry_report__industry=Industry_obj)

    context = {
        'industry' : Industry_obj,
        'Industry_Report' : Industry_Report_obj,
        'report_tableA' : report_tableA_obj,
    }

    # 获取内存中生成的PDF字节内容
    pdf_content = render_to_pdf('app/pdf_rprt.html', context)
    if pdf_content:
        to = "kanchon2199@gmail.com"
        email = EmailMultiAlternatives(
            subject="final report sending (beta)",
            body='hello, this is test report sending mail',
            from_email=settings.EMAIL_HOST_USER,
            to=[to]
        )
        # 直接将内存中的PDF字节作为附件附加,无需读取本地文件
        email.attach(
            filename="industry_report.pdf",
            content=pdf_content,
            mimetype="application/pdf"
        )
        email.send()

    return redirect('app:index')
关键注意点
  • 两种邮件附件方法的适用场景区分:
    • attach_file():入参为本地磁盘上的真实文件路径,方法会自动读取文件内容、识别MIME类型后附加到邮件
    • attach():入参为自定义文件名、内存中的文件二进制内容、指定MIME类型,不需要文件落地到磁盘,适配动态生成的文件场景
  • 原函数中使用可变字典作为默认参数context_dict={}是Python语法的常见坑,多次调用函数时会残留上一次传入的context值,需调整为None作为默认值,在函数内部初始化空字典。

内容的提问来源于stack exchange,提问作者Kanchon Gharami

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.09 11:36:04