我一直在努力通过电子邮件发送pdf文件(使用weasy print),我希望能够直接发送电子邮件而不将文件保存在我的模型对象中(如果我可以将其保存在临时位置并通过电子邮件发送它)。但继续得到这个错误。 ' file()参数1必须是没有空字节的编码字符串,而不是str
pdf_file = HTML(string=rendered_html,
base_url=settings.MEDIA_ROOT).write_pdf()
certificate = SimpleUploadedFile(
'Certificate-' + '.pdf', pdf_file, content_type='application/pdf')
attachment = certifcate.read()
msg.attach_file(attachment, 'application/pdf')
答案 0 :(得分:0)
我能够动态生成pdf文件,将其保存到临时位置并通过电子邮件发送。我停止使用SimpleUploadedFile
并使用NamedTemporaryFile
python模块中的tempfile
函数。它允许您返回一个类似文件的对象,该对象可以用作临时存储区域,您可以向其写入内容,从中读取它。这里是文档的link和tempfile上的blog的一些引用
pdf_file = HTML(string=rendered_html,
base_url=settings.MEDIA_ROOT).write_pdf()
temp = tempfile.NamedTemporaryFile()
temp.write(pdf_file)
temp.seek(0)
msg = EmailMultiAlternatives(
subject, message, sender, receivers)
msg.attach_file(temp.name, 'application/pdf')
msg.send()