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...)
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!