views:

210

answers:

2

I have a django app that dynamically generates a PDF (using reportlab + pypdf) from user input on an HTML form, and returns the HTTP response with an application/pdf MIMEType.

I want to have the option between doing the above, or emailing the generated pdf, but I cannot figure out how to use the EmailMessage class's attach(filename=None, content=None, mimetype=None) method. The documentation doesn't give much of a description of what kind of object content is supposed to be. I've tried a file object and the above application/pdf HTTP response.

I currently have a workaround where my view saves a pdf to disk, and then I attach the resulting file to an outgoing email using the attach_file() method. This seems wrong to me, and I'm pretty sure there is a better way.

A: 

Based on the example in your link:

message.attach('design.png', img_data, 'image/png')

Wouldn't your content for a pdf just be the same output that you would normally write to the pdf file? Instead of saving the generated_pdf_data to myfile.pdf, plug it into the content field of the message.attach:

message.attach('myfile.pdf', generated_pdf_data, 'application/pdf')
Lee
I'm not sure how to generate the pdf data in a format that the attach() function would understand.
Shane
If you're going to actually write it out to the file anyway, might as well use attach_file() and save the open() line. This might help with the 'in memory' attaching. http://two.pairlist.net/pipermail/reportlab-users/2009-April/008206.html
Lee
A: 

Ok I've figured it out.

The second argument in attach() expects a string. I just used a file object's read() method to generate what it was looking for:

from django.core.mail import EmailMessage

message = EmailMessage('Hello', 'Body goes here', '[email protected]',
    ['[email protected]', '[email protected]'], ['[email protected]'],
    headers = {'Reply-To': '[email protected]'})
attachment = open('myfile.pdf', 'rb')
message.attach('myfile.pdf',attachment.read(),'application/pdf')

I ended up using a tempfile instead, but the concept is the same as an ordinary file object.

Shane
Reportlab and pyPdf can both use StringIO or cStringIO objects, so you won't have to use temporary files.
AKX