Send email with ZIP attachments in Python

This is the place for queries that don't fit in any of the other categories.

Send email with ZIP attachments in Python

Postby bviswanathan » Thu Apr 11, 2013 8:07 pm


I am trying to send an email with ZIP file as an attachment in Python. Here is how I am doing it.

Code: Select all
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
    assert type(send_to)==list
    assert type(files)==list

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for f in files:
        remotezip = urllib2.urlopen(f)
        zipinmemory = io.BytesIO(
        zip = zipfile.ZipFile(zipinmemory)
        part = MIMEBase('application', 'octet-stream') #part=MIMEBASE('application','zip') doesn't work

        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))

    smtp = smtplib.SMTP('')
    smtp.login('abc','xyz') #Username,Password
    smtp.sendmail(send_from, send_to, msg.as_string())

I have my zip file hosted on my web server, so I had to use URLOpen to get the ZIP file. This code sends the zip file to the user, but the attachment is always 0KB. I am not sure where the error is.

Kindly let me know. Thanks for your help!!

Balaji Viswanathan.
Posts: 1
Joined: Thu Apr 11, 2013 7:58 pm

Re: Send email with ZIP attachments in Python

Postby stranac » Thu Apr 11, 2013 9:24 pm

There is no reason to use zipfile here.
You can just pass the data you read from the web to part.set_payload().

Also, application/zip works fine, just make sure MIMEBase has correct capitalization.

You should end up with something like this:
Code: Select all
part = MIMEBase('application', 'zip')
                'attachment; filename="%s"' % os.path.basename(zip_url))
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
Posts: 1412
Joined: Thu Feb 07, 2013 3:42 pm

Return to General Coding Help

Who is online

Users browsing this forum: Jorgalad and 3 guests