我使用docx创建了一个文档,并尝试在不将文档保存在服务器上的情况下作为电子邮件附件发送。以下是我的代码:
Document = document()
paragraph = document.add_paragraph("Test Content")
f = BytesIO()
document.save(f)
file_list = []
file_list.append(["Test.docx",f, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
email = EmailMessage(subject = 'Test', body = 'Hi', to = ['test@test.com'], attachments = file_list)
email.send()
我得到以下错误:
类型错误:应为类似对象的字节,而不是BytesIO
在线email.send()
上
我尝试将BytesIO转换为StringIO,如所述
f = f.read()
f = StringIO(f.decode('UTF-8'))
然后我得到错误:
TypeError:应为类似对象的字节,而不是StringIO
我从中查看了解决方案,但不明白document
是如何作为附件发送的。
任何帮助或建议都将不胜感激。
谢谢!
答案在错误消息中。
代替
file_list.append(["Test.docx",f, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
我做了
file_list.append(["Test.docx", f.getValue(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
因为在我的代码中,f
是一个BytesIO
对象,而f.getValue()
将对象的内容返回为bytes
。
文件:https://docs.python.org/3/library/io.html#io.BytesIO.getvalue