繁体   English   中英

将Word文档附加到电子邮件并发送,而无需在python中本地保存

[英]Attach a word document to an e-mail and send without saving locally in python

我有一个可以创建Word文档的应用程序,我需要将其发送出去而不将其保存在本地。 换句话说,我需要发送一个对象。 我知道下面的代码不起作用,因为我的文档是一个对象。 有什么办法吗?

TypeError:强制转换为Unicode:需要字符串或缓冲区,找到文档

有谁知道如何做到这一点? 这是我所拥有的:

def document_writer():
document = Document()
document.add_heading('Sample Document', 0)
document.add_paragraph("fsfsa")

document.add_heading('Addresses', 2)


return document

def mailsend(send_from, send_to, subject, text, login, password, document, files=None,
          smtpserver='smtp.gmail.com:587'):

msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', "octet-stream")
part.set_payload(open(document, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="crap.docx"')
msg.attach(part)
server = smtplib.SMTP(smtpserver)
server.starttls()
#server.starttls()
server.login(login, password)
server.sendmail(send_from, send_to, msg.as_string())

server.close()

在代码中的某个点上,函数需要一个string但是会得到一个Document类,而python则不知道如何将其转换为string

在函数document_writer您正在创建此类Document因此,您应检查在何处使用此类创建的Document对象。

要解决此问题,可以采取三种解决方案:

  1. Document类可以转换为字符串。 那你就可以做str(Document)
  2. 该文档类不能通过str()转换为字符串,但是具有特殊的功能。 然后,您可以只执行document_variable.convert_to_str_function()
  3. 您可以将此Document类作为文件保存到磁盘。 然后,您应该看看这些答案: 二进制文件电子邮件附件问题 ,通过电子邮件发送基于磁盘的文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM