附上pdf';django中的电子邮件

附上pdf';django中的电子邮件,django,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()

我的应用程序使用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')
医生说():

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

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

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

从django.core.mail导入EmailMessage

pdf_file=model_instance.file#请看这里如何将文件附加到电子邮件:然后你做了什么?选定的答案不是很清楚。