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

Aur*_*ien 1 pdf django email-attachments django-email

这个问题在这里有一些元素,但没有最终答案。

有使用easy_pdf生成PDF的视图

from easy_pdf.views import PDFTemplateResponseMixin

class PostPDFDetailView(PDFTemplateResponseMixin,DetailView):
    model = models.Post
    template_name = 'post/post_pdf.html'
Run Code Online (Sandbox Code Playgroud)

然后,我想将此生成的 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()
Run Code Online (Sandbox Code Playgroud)

我也试过这个:

   msg.attach_file(domain + '/post/' + post_id + '.pdf', 'application/pdf')
Run Code Online (Sandbox Code Playgroud)

小智 5

我一直在寻找一种方法来附加一个 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')
Run Code Online (Sandbox Code Playgroud)

如果您仍然对这样做感兴趣,我希望它会有所帮助。