Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching pdf's to emails in django

Tags:

django

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

Here is my pdf view:

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')
like image 767
user3972986 Avatar asked Oct 19 '15 15:10

user3972986


People also ask

How do I email a PDF in Django?

attach("document. pdf", pdf_file. read())' you can take your instance of PDFTemplateResponse (let's call the instance variable "res") and use 'message. attach("document.


1 Answers

The docs say (https://docs.djangoproject.com/en/dev/topics/email/#the-emailmessage-class):

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.

So you have to create an EmailMessage:

from django.core.mail import EmailMessage

email = EmailMessage(
    'Subject here', 'Here is the message.', '[email protected]', ['[email protected]'])
email.attach_file('Document.pdf')
email.send()
like image 73
xbello Avatar answered Oct 07 '22 06:10

xbello