【问题标题】:Attaching pdf's to emails in django将pdf附加到django中的电子邮件
【发布时间】:2016-01-18 01:10:16
【问题描述】:

我的应用程序使用 django-wkhtmltopdf 生成 pdf 报告。我希望能够将 pdf 附加到电子邮件并发送。

这是我的 pdf 视图:

class Report(DetailView):
    template = 'pdf_reports/report.html'
    model = Model

    def get(self, request, *args, **kwargs):
        self.context['model'] = self.get_object()

        response=PDFTemplateResponse(request=request,
                                     template=self.template,
                                     filename ="report.pdf",
                                     context=self.context,
                                     show_content_in_browser=False,
                                     cmd_options={'margin-top': 0,
                                                  'margin-left': 0,
                                                  'margin-right': 0}
                                     )
        return response

这是我的电子邮件视图:

def email_view(request, pk):
    model = Model.objects.get(pk=pk)
    email_to = model.email
    send_mail('Subject here', 'Here is the message.', 'from',
    [email_to], fail_silently=False)

    response = HttpResponse(content_type='text/plain')
    return redirect('dashboard')

【问题讨论】:

标签: django


【解决方案1】:

文档说 (https://docs.djangoproject.com/en/dev/topics/email/#the-emailmessage-class):

并非 EmailMessage 类的所有功能都可以通过 send_mail() 和相关的包装函数获得。如果您希望使用高级功能,例如密件抄送收件人、文件附件或多部分电子邮件,则需要直接创建 EmailMessage 实例。

所以你必须创建一个EmailMessage

from django.core.mail import EmailMessage

email = EmailMessage(
    'Subject here', 'Here is the message.', 'from@me.com', ['email@to.com'])
email.attach_file('Document.pdf')
email.send()

【讨论】:

    【解决方案2】:

    如果要附加存储在内存中的文件,只需使用 attach

    msg = EmailMultiAlternatives(mail_subject, text_content, settings.DEFAULT_FROM_EMAIL, [instance.email])
    msg.attach_alternative(message, "text/html")
    pdf = render_to_pdf('some_invoice.html')
    msg.attach('invoice.pdf', pdf)
    msg.send()
    

    【讨论】:

      【解决方案3】:

      一种情况是文件保存在磁盘上(例如,在存储库中)并通过固定路径访问。在模型中使用该字段更安全(并且可能更容易)。假设 PDF 文件存储在某个 model_instance 对象的 FileField 中:

      from django.core.mail import EmailMessage
      
      pdf_file = model_instance.file  # <- here I am accessing the file attribute, which is a FileField
      message = EmailMessage(
          "Subject",
          "Some body."
          "From@example.com",
          [email_to],
      )
      message.attach("document.pdf", pdf_file.read())
      message.send(fail_silently=False) 
      

      【讨论】:

      • 代替 'message.attach("document.pdf", pdf_file.read())' 您可以获取 PDFTemplateResponse 实例(我们将实例变量称为“res”)并使用 'message.附加(“document.pdf”,res.rendered_content)'。然后您可以使用生成的 PDF 而无需先将其保存到文件系统。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多