将pdf附加到django中的电子邮件中

时间:2015-10-19 15:42:29

标签: django

我的应用使用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')

3 个答案:

答案 0 :(得分:5)

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

  

并非所有EmailMessage类的功能都可通过send_mail()和相关的包装函数获得。如果您希望使用高级功能,例如BCC的收件人,文件附件或多部分电子邮件,则需要直接创建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()

答案 1 :(得分:1)

如果要附加存储在内存中的文件,则仅使用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()

答案 2 :(得分:0)

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

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)