Reputation: 712
I have been struggling to email a pdf file am generating(using weasy print),I would like to be able to email directly without saving the file in my model object(If I could just save it in a temporary location and email it).But keep Getting this error. 'file() argument 1 must be encoded string without null bytes, not str
pdf_file = HTML(string=rendered_html,
base_url=settings.MEDIA_ROOT).write_pdf()
certificate = SimpleUploadedFile(
'Certificate-' + '.pdf', pdf_file, content_type='application/pdf')
attachment = certifcate.read()
msg.attach_file(attachment, 'application/pdf')
Upvotes: 2
Views: 1907
Reputation: 712
I was able to generate pdf file on the fly,save it to a temporary location and email it.I stopped using SimpleUploadedFile
and used the NamedTemporaryFile
function from tempfile
python module.it allows you to return a file-like object that can be used as a temporary storage area, which you can write something to it, read it from it. here is the link to docs and some reference to a blog on tempfile
pdf_file = HTML(string=rendered_html,
base_url=settings.MEDIA_ROOT).write_pdf()
temp = tempfile.NamedTemporaryFile()
temp.write(pdf_file)
temp.seek(0)
msg = EmailMultiAlternatives(
subject, message, sender, receivers)
msg.attach_file(temp.name, 'application/pdf')
msg.send()
Upvotes: 2