Django - 将PDF格式视图生成的电子邮件附加到电子邮件中
问题描述:
此问题有一些元素here,但没有最终答案。Django - 将PDF格式视图生成的电子邮件附加到电子邮件中
有视图生成PDF与easy_pdf
from easy_pdf.views import PDFTemplateResponseMixin
class PostPDFDetailView(PDFTemplateResponseMixin,DetailView):
model = models.Post
template_name = 'post/post_pdf.html'
然后,我想附上这个生成的PDF至以下邮箱:
@receiver(post_save, sender=Post)
def first_mail(sender, instance, **kwargs):
if kwargs['created']:
user_email = instance.client.email
subject, from_email, to = 'New account', '[email protected]', user_email
post_id = str(instance.id)
domain = Site.objects.get_current().domain
post_pdf = domain + '/post/' + post_id + '.pdf'
text_content = render_to_string('post/mail_post.txt')
html_content = render_to_string('post/mail_post.html')
# create the email, and attach the HTML version as well.
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.attach_file(post_pdf, 'application/pdf')
msg.send()
我也试过这样:
msg.attach_file(domain + '/post/' + post_id + '.pdf', 'application/pdf')
答
不知道它是否有帮助,但我用内置的EmailMessage来附加我创建的PDF以电子邮件报告我送出:
from django.core.mail import send_mail, EmailMessage
draft_email = EmailMessage(
#subject,
#body,
#from_email,
#to_email,
)
选项1:
# attach a file you have saved to the system... expects the path
draft_email.attach_file(report_pdf.name)
选项2:
# expects the name of the file object
draft_email.attach("Report.pdf")
然后发送您已经有:
draft_email.send()
一些最初的想法:这似乎是你想要的使用attach_file从系统附加文件,但它不在系统中。我会尝试使用attach
而不是attach_file
,如果我正确读取您的代码,因为pdf在您的内存中,而不是系统中的LTS。
答
我正在寻找一种方法来附加easy_pdf生成的PDF,而不保存临时文件。因为我无法在其他地方找到一个解决办法,我建议使用easy_pdf.rendering.render_to_pdf短和工作建议:
from easy_pdf.rendering import render_to_pdf
...
post_pdf = render_to_pdf(
'post/post_pdf.html',
{'any_context_item_to_pass_to_the_template': context_value,},
)
...
msg.attach('file.pdf', post_pdf, 'application/pdf')
我希望它会帮助,如果你仍然有兴趣通过一种方式来做到这一点。
我认为问题出现是因为在请求视图时生成PDF,所以它不能附加到电子邮件。你对此有何看法? –
当文件未被创建时,我没有使用附件的问题...可能值得尝试。假设文件在试图将其附加到电子邮件时仍处于打开状态并处于缓存中。你能分享你的错误吗? – Doug
使用easy_pdf时,PDF未保存在某处。它只是生成。所以文件report.pdf不存在。 –