【问题标题】:Create a document using python-docx and send as attachment through django使用 python-docx 创建一个文档并通过 django 作为附件发送
【发布时间】:2019-05-05 03:19:01
【问题描述】:

我使用 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:预期的类似字节的对象,而不是 BytesIO

上线email.send()

我尝试将 BytesIO 转换为 StringIO,如 here 所述

f = f.read()
f = StringIO(f.decode('UTF-8'))

然后我得到错误:

TypeError:预期的类似字节的对象,而不是 StringIO

我查看了this 的解决方案,但不明白document 是如何作为附件发送的。

感谢任何帮助或指点。

谢谢!

【问题讨论】:

    标签: python django email email-attachments python-docx


    【解决方案1】:

    答案在错误信息中。

    代替

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 2016-12-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 2017-07-05
      相关资源
      最近更新 更多