Django, ReportLab PDF Generation attached to an email

后端 未结 3 1758
生来不讨喜
生来不讨喜 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-09 00:12

    Using ReportLab

    
    try:
        from cStringIO import StringIO
    except ImportError:
        from StringIO import StringIO
    from reportlab.pdfgen import canvas
    from reportlab.lib.pagesizes import letter, A4
    from reportlab.lib.units import inch
    
    def createPDF(request):
     x=100
     y=100
     buffer=StringIO()
     p=canvas.Canvas(buffer,pagesize=letter)
     p.drawString(x,y,"HELLOWORLD")
     p.showPage()
     p.save() 
     pdf=buffer.getvalue()
     buffer.close() 
     return pdf
    
    def someView(request):
     EmailMsg=mail.EmailMessage(YourSubject,YourEmailBodyCopy,'email@email.com',["email@email.com"],headers={'Reply-To':'email@email.com'})
     pdf=createPDF(request)
     EmailMsg.attach('yourChoosenFileName.pdf',pdf,'application/pdf')
     EmailMsg.send()
    

    Works perfectly!!

提交回复
热议问题