这个问题有一些要素here ,但没有最终答案。
有使用easy_pdf生成PDF的 View
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', 'contact@example.com', 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')
最佳答案
我一直在寻找一种方法来附加 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')
如果您仍然对执行此操作的方法感兴趣,我希望它能有所帮助。
关于Django - 将 View 生成的 PDF 附加到电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46567889/