使用 Django 和 ReportLab 生成 PDF 并将其附加到电子邮件的最佳方法是什么?
我正在使用 SimpleDocTemplate,并且可以将生成的 PDF 附加到我的 HttpResponse - 这很棒,但我无法找到如何将相同的附件准确添加到电子邮件中:
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=invoice.pdf'
doc = SimpleDocTemplate(response, pagesize=letter)
Document = []
...通过将表格附加到文档中来制作我的 pdf...
doc.build(Document)
email = EmailMessage('Hello', 'Body', '[email protected] /cdn-cgi/l/email-protection', ['[email protected] /cdn-cgi/l/email-protection'])
email.attach('invoice.pdf', ???, 'application/pdf')
email.send()
我只是不确定如何将我的 pdfdocument 翻译为 blob,以便 email.attach 可以接受它并且 email.send 可以发送它。
有任何想法吗?
使用报告实验室
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib.units import inch
def createPDF(request):
x=100
y=100
buffer=StringIO()
p=canvas.Canvas(buffer,pagesize=letter)
p.drawString(x,y,"HELLOWORLD")
p.showPage()
p.save()
pdf=buffer.getvalue()
buffer.close()
return pdf
def someView(request):
EmailMsg=mail.EmailMessage(YourSubject,YourEmailBodyCopy,'[email protected] /cdn-cgi/l/email-protection',["[email protected] /cdn-cgi/l/email-protection"],headers={'Reply-To':'[email protected] /cdn-cgi/l/email-protection'})
pdf=createPDF(request)
EmailMsg.attach('yourChoosenFileName.pdf',pdf,'application/pdf')
EmailMsg.send()
完美运作!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)