1

我想从 python 发送一封电子邮件:

thedoc = generate_doc()

mail.send_mail(sender="Support",
              to="user@mail.co.uk",
              subject="RE: ref",
              attachments=('thedoc.docx', thedoc),
              body="""Blah blah blah""")

这里是generate_doc()

zin = zipfile.ZipFile("template/thedoc.docx",'r')
zout = zipfile.ZipFile(in_memory_zip, "a", zipfile.ZIP_DEFLATED, False)

in_memory_zip = StringIO.StringIO()

for item in zin.infolist():
    buffer = zin.read(item.filename)
        zout.writestr(item, buffer)

# sets windows as the create system to avoid unix file permissions
for zfile in zout.filelist:
    zfile.create_system = 0

zin.close()
    zout.close()

in_memory_zip.seek(0)

#return in_memory_zip.getvalue() <--- This is usual return

f = file('random.docx', "w")      <--- this is test to try and diagnose
f.write(in_memory_zip.getvalue()) <--- the file written here opens correctly
f.close()

邮件发送成功,但附件 .docx 无法在 word/pages/skydrive 中打开,似乎已损坏(并且比本地写入的文件略大)

如果我在本地编写文件而不是作为附件发送,它会正确打开。

我需要f.write(in_memory_zip.getvalue())在作为附件发送之前进行模拟吗?

如果是这样,怎么做?否则我还能做些什么来诊断问题?

4

0 回答 0