Django, ReportLab PDF Generation attached to an email

Daniel D picture Daniel D · Dec 7, 2010 · Viewed 7.4k times · Source

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 my HttpResponse - which is great, but I'm having trouble finding out how to exactly add that same attachment to an email:

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=invoice.pdf'
    doc = SimpleDocTemplate(response, pagesize=letter)
    Document = []

... make my pdf by appending tables to the Document...

  doc.build(Document)
  email = EmailMessage('Hello', 'Body', '[email protected]', ['[email protected]'])
  email.attach('invoice.pdf', ???, 'application/pdf')
  email.send()

I'm just not sure how to translate my pdfdocument as a blob so that email.attach can accept it and email.send can send it.

Any ideas?

Answer

magicTuscan picture magicTuscan · Dec 9, 2010

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 protected]',["[email protected]"],headers={'Reply-To':'[email protected]'})
 pdf=createPDF(request)
 EmailMsg.attach('yourChoosenFileName.pdf',pdf,'application/pdf')
 EmailMsg.send()

Works perfectly!!