Django - 将 View 生成的 PDF 附加到电子邮件

标签 django pdf email-attachments django-email

这个问题有一些要素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/

相关文章:

python - Django 中的同时多任务处理

python - 求和 Django 中的记录值

python - Django django.db.utils.ProgrammingError。关系 <<Pages_account>> 不存在

Android:在后台自动发送带附件的电子邮件

android - 尝试将创建的文本文件作为电子邮件附件发送 - 从默认文件夹

python - google-app-engine 的最佳全文搜索

python - 如何从 Python 中填写的表单中提取 PDF 字段?

bash - 如何在 shell 中为 graphicsmagick 编写循环?

PHP Safari PDF转图片问题

vba - 使用Outlook VBA区分可见和不可见附件