Django, ReportLab PDF Generation attached to an email

后端 未结 3 1762
生来不讨喜
生来不讨喜 2021-02-08 23:43

What\'s the best way to use Django and ReportLab to generate PDFs and attach them to an email message?

I\'m using a SimpleDocTemplate and can attach the generated PDF to

3条回答
  •  花落未央
    2021-02-09 00:39

    I don't see where your blob is rendered, so I can't advise you on how to import it. I've gotten great results using Pisa and StringIO:

    import ho.pisa as pisa
    import StringIO
    from django.template.loader import render_to_string
    from django.core.mail import EmailMessage
    
    render = render_to_string("books/agreement/agreement_base.html",
                                  { "title": book.title,
                                    "distribution": book.distribution_region })
    out = StringIO.StringIO()
    pdf = pisa.CreatePDF(StringIO.StringIO(render), out)
    email = EmailMessage('Hello', 'Body', 'from@from.com', ['to@to.com'])
    email.attach('agreement.pdf', out.getvalue(), 'application/pdf')
    email.send()
    

    That said, if your PDF exists as an independent and persistent document on your filesystem, couldn't you just:

    email.attach('agreement.pdf', open('agreement.pdf', 'rb').read(), 'application/pdf')
    

提交回复
热议问题