在django中将pdf附加到电子邮件 [英] Attaching pdf's to emails in django

查看:61
本文介绍了在django中将pdf附加到电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My app produces pdf reports using django-wkhtmltopdf. I want to be able to attach the pdf to an email and send.

这是我的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

这是我的电子邮件视图:

And here is my email view:

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')

推荐答案

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

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

Not all features of the EmailMessage class are available through the send_mail() and related wrapper functions. If you wish to use advanced features, such as BCC’ed recipients, file attachments, or multi-part email, you’ll need to create EmailMessage instances directly.

所以您必须创建一个 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()

这篇关于在django中将pdf附加到电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆