Shiva Krishna Bavandla
Shiva Krishna Bavandla

Reputation: 26748

How can I send an email with a zip file attached in Python?

I have a zip folder named csv in my directory here:

I would like to send an email with this zip folder as an attachment.

Until now I have sent emails from Python by using the smtplib module, but I don't know how to send an email with a zip folder as an attachment.

I have searched on Google, but the code I’ve found is for compressing and sending an email, not attaching a zip to file to an email.

Upvotes: 1

Views: 8237

Answers (2)

Vimal Menon
Vimal Menon

Reputation: 59

Say the zip file you wish to attach is '/home/local/user/project/zip_module/csv.zip', and to, sender, subject and text contain your to address, from address, the subject and mail text respectively.

Then,

import smtplib, MimeWriter, mimetools, base64

message = StringIO.StringIO()
email_msg = MimeWriter.MimeWriter(message)
email_msg.addheader('To', to)
email_msg.addheader('From', sender)
email_msg.addheader('Subject', subject)
email_msg.addheader('MIME-Version', '1.0')

email_msg.startmultipartbody('mixed')

part = email_msg.nextpart()
body = part.startbody('text/plain')
part.flushheaders()
body.write(text)

file_to_attach = '/home/local/user/project/zip_module/csv.zip'
filename = os.path.basename(file_to_attach)
ftype, encoding = 'application/zip', None

part = email_msg.nextpart()
part.addheader('Content-Transfer-Encoding', encoding)
body = part.startbody("%s; name=%s" % (ftype, filename))
mimetools.encode(open(file_to_attach, 'rb'), body, encoding)

email_msg.lastpart()

email_text = message.getvalue()

Now send the email like you did using smtplib, with email_text as msg

e.g.

smtp = smtplib.SMTP(SERVER, PORT)
smtp.login(USER, PASSWORD)
smtp.sendmail(sender, to, email_text)
smtp.quit()

Upvotes: 3

Simon
Simon

Reputation: 12508

Try the email package from the standard library. It lets you construct multipart MIME messages which can contain a text/plain part (for the text you want to send) and an application/zip part for the ZIP file. You can then serialize the message to a string and send that using smtplib.

Upvotes: 2

Related Questions