1

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?

Awalias
  • 2,027
  • 6
  • 31
  • 51
  • 1
    Take a look at the raw mail message ("view message source") and find the Content-Type generated for the MIME part corresponding to the `thedoc.docx` attachment. If it's `text/`, then the receiving mailer is probably performing LF->CRLF conversion when saving the ZIP on Windows. That explains the corruption and the "slightly larger in size" observation. – user4815162342 Apr 02 '13 at 15:56
  • Ok the type is `application/msword` with `MIME-Version: 1.0` – Awalias Apr 02 '13 at 21:20
  • I sent the 'valid' file via email and it shows up with type `Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document` `Content-Transfer-Encoding: base64` is there a way I can force these with the mail api? – Awalias Apr 02 '13 at 21:44
  • 1
    `application/msword` should be fine. Can you manually decode the base64 block to see if the contents is corrupted? You might want to compare it to the contents of `f.write(in_memory_zip.getvalue().replace('\n', '\r\n'))`. I still suspect that they will end up the same. – user4815162342 Apr 02 '13 at 21:57

0 Answers0