使用 python-docx 创建文档并通过 django 作为附件发送
Create a document using python-docx and send as attachment through django
我使用 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()
我收到以下错误:
TypeError: expected bytes-like object, not BytesIO
上线email.send()
我尝试将 BytesIO 转换为 StringIO,如前所述 here
f = f.read()
f = StringIO(f.decode('UTF-8'))
然后我得到错误:
TypeError: expected bytes-like object, not 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()
returns对象的内容为bytes
。
文档:https://docs.python.org/3/library/io.html#io.BytesIO.getvalue
我使用 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()
我收到以下错误:
TypeError: expected bytes-like object, not BytesIO
上线email.send()
我尝试将 BytesIO 转换为 StringIO,如前所述 here
f = f.read()
f = StringIO(f.decode('UTF-8'))
然后我得到错误:
TypeError: expected bytes-like object, not 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()
returns对象的内容为bytes
。
文档:https://docs.python.org/3/library/io.html#io.BytesIO.getvalue