动态生成PDF并使用django通过电子邮件发送 [英] Dynamically generate PDF and email it using django

查看:183
本文介绍了动态生成PDF并使用django通过电子邮件发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django应用程序,该应用程序通过HTML表单上的用户输入动态生成PDF(使用reportlab + pypdf),并返回HTTP响应以及 application / pdf MIMEType。

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.

我想在执行上述操作或通过电子邮件发送生成的pdf之间进行选择,但我不知道如何使用EmailMessage类的 attach(filename = None,content = None,mimetype = None)方法。 文档并没有太多描述 content 应该是什么样的对象。我已经尝试了一个文件对象和上面的 application / pdf HTTP响应。

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.

我目前有一种解决方法,其中我的视图将pdf保存到磁盘,然后使用 attach_file()方法将结果文件附加到外发电子邮件中。对我来说这似乎是错的,我很确定有更好的方法。

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.

推荐答案

好,我已经弄清楚了

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

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', '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')

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

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

这篇关于动态生成PDF并使用django通过电子邮件发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆