附加pdf到django的电子邮件
问题描述:
我的应用程序使用django-wkhtmltopdf生成pdf报告。我希望能够将pdf附加到电子邮件并发送。附加pdf到django的电子邮件
这里是我的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')
答
文档说(https://docs.djangoproject.com/en/1.8/topics/email/#the-emailmessage-class):
并非所有的EmailMessage的特点类可以通过send_mail()和相关的包装函数获得。如果您希望使用高级功能,例如BCC的收件人,文件附件或多部分电子邮件,则需要直接创建EmailMessage实例。
所以,你必须创建一个EmailMessage
:
email = EmailMessage(
'Subject here', 'Here is the message.', '[email protected]', [[email protected]])
email.attach_file('Document.pdf')
email.send()
看到这里如何将文件附加到电子邮件:http://stackoverflow.com/questions/9541837/attach-a-txt-file -in的Python-的smtplib – Anentropic