I want to send an email from python with:
thedoc = generate_doc()
mail.send_mail(sender="Support",
to="user@mail.co.uk",
subject="RE: ref",
attachments=('thedoc.docx', thedoc),
body="""Blah blah blah""")
Here is 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()
The email is sent successfully but the attached .docx will not open in word/pages/skydrive, seems to be corrupt (and is slightly larger in size than the file written locally)
If I write the file locally instead of sending as attachment, it opens correctly.
Do I need to simulate f.write(in_memory_zip.getvalue())
before sending as attachment?
If so, how? Or else what else can I do to diagnose the problem?