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

Hi,

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(remotezip.read())
        zip = zipfile.ZipFile(zipinmemory)
        part = MIMEBase('application', 'octet-stream') #part=MIMEBASE('application','zip') doesn't work

     
        part.set_payload( remotezip.read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)
       

    smtp = smtplib.SMTP('smtp.gmail.com:587')
    smtp.starttls()
    smtp.login('abc','xyz') #Username,Password
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()


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.
bviswanathan
 
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')
part.set_payload(urllib2.urlopen(zip_url).read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
                'attachment; filename="%s"' % os.path.basename(zip_url))
msg.attach(part)
Friendship is magic!

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


Return to General Coding Help

Who is online

Users browsing this forum: snippsat and 6 guests