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')
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With