动态生成PDF并使用django通过电子邮件发送

Sha*_*ane 8 email django email-attachments

我有一个django应用程序,它从HTML表单上的用户输入动态生成PDF(使用reportlab + pypdf),并返回带有application/pdfMIMEType 的HTTP响应.

我希望在执行上述操作或通过电子邮件发送生成的pdf之间进行选择,但我无法弄清楚如何使用EmailMessage类的attach(filename=None, content=None, mimetype=None)方法.该文档没有给出对content应该是什么类型的对象的大量描述.我已经尝试过一个文件对象和上面的application/pdfHTTP响应.

我目前有一个解决方法,我的视图将pdf保存到磁盘,然后我使用该attach_file()方法将生成的文件附加到外发电子邮件.这对我来说似乎不对,我很确定有更好的方法.

Sha*_*ane 6

好的,我已经弄清楚了.

第二个参数attach()需要一个字符串.我只是使用文件对象的read()方法来生成它正在寻找的东西:

from django.core.mail import EmailMessage

message = EmailMessage('Hello', 'Body goes here', 'from@example.com',
    ['to1@example.com', 'to2@example.com'], ['bcc@example.com'],
    headers = {'Reply-To': 'another@example.com'})
attachment = open('myfile.pdf', 'rb')
message.attach('myfile.pdf',attachment.read(),'application/pdf')
Run Code Online (Sandbox Code Playgroud)

我最终使用的是tempfile,但概念与普通文件对象相同.

  • Reportlab和pyPdf都可以使用StringIO或cStringIO对象,因此您不必使用临时文件. (3认同)

Lee*_*Lee 0

根据您链接中的示例:

message.attach('design.png', img_data, 'image/png')
Run Code Online (Sandbox Code Playgroud)

您的 pdf 内容难道不会与您通常写入 pdf 文件的输出相同吗?不要将 generated_pdf_data 保存到 myfile.pdf,而是将其插入 message.attach 的内容字段:

message.attach('myfile.pdf', generated_pdf_data, 'application/pdf')
Run Code Online (Sandbox Code Playgroud)