0

Example file: https://drive.google.com/file/d/14lkiAllI6To6WXlub8VEe5NNBzZssFFz/view?usp=sharing

Example code:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase

SMTP = "example.com:587"
TO = "example@example.com"
USERNAME = "example@example.com"
PASSWORD = "hunter2"
zip_filename = "testfile.zip"

msg = MIMEMultipart("mixed")
msg["Subject"] = "Subject"
msg["From"] = USERNAME
msg["To"] = TO
msg.attach(MIMEText("Test messsage", "html"))

attachment = MIMEBase("application", "zip")
with open(zip_filename, 'rb') as created_zipfile:
    attachment.set_payload(created_zipfile.read())
    attachment.add_header('Content-Disposition', 'attachment;filename="%s"' % zip_filename)
    msg.attach(attachment)

server = smtplib.SMTP(SMTP)
server.ehlo()
server.starttls()
server.login(USERNAME, PASSWORD)
server.sendmail(USERNAME, TO, msg.as_string())
server.quit()

The original file is valid, and can be opened by 7Zip. The file received by email is identical (when I open both in Notepad++ and hit "Compare", it says they match), but Windows won't open it. When I use 7Zip's "Test archive" feature, it says it's not an archive.

I am surprised that Notepad++ says they're identical, but there is clearly some (meta?) difference. I'm using Windows, but Windows explorer isn't showing any obvious difference in Properties. I've found that some CSV files are fine, but haven't worked out what causes differences. I'm using Python 2.7.15 (but meaning to update to Python 3 soon...)

Chris
  • 585
  • 3
  • 12
  • 26
  • There's always a possibility that my email server is mangling the attachment - if you don't manage to reproduce it, then let me know I can provide the 'output' file too. – Chris Sep 18 '19 at 19:12

1 Answers1

0

I needed to add:

encoders.encode_base64(attachment)

(this could be done even after attaching it to the msg). I found this line in How to send a zip file as an attachment in python?. Thanks for rubber-ducking for me anyway!

Chris
  • 585
  • 3
  • 12
  • 26