I would like to compress a folder and all its sub-folders/files, and email the zip file as an attachment. What would be the best way to achieve this with Python?
+8
A:
You can use the zipfile module to compress the file using the zip standard, the email module to create the email with the attachment, and the smtplib module to send it - all using only the standard library.
Python - Batteries Included
If you don't feel like programming and would rather ask a question on stackoverflow.org instead, or (as suggested in the comments) left off the homework
tag, well, here it is:
import smtplib
import zipfile
import tempfile
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
def send_file_zipped(the_file, recipients, sender='[email protected]'):
zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip')
zip = zipfile.ZipFile(zf, 'w')
zip.write(the_file)
zip.close()
zf.seek(0)
# Create the message
themsg = MIMEMultipart()
themsg['Subject'] = 'File %s' % the_file
themsg['To'] = ', '.join(recipients)
themsg['From'] = sender
themsg.preamble = 'I am not using a MIME-aware mail reader.\n'
msg = MIMEBase('application', 'zip')
msg.set_payload(zf.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment',
filename=the_file + '.zip')
themsg.attach(msg)
themsg = themsg.as_string()
# send the message
smtp = smtplib.SMTP()
smtp.connect()
smtp.sendmail(sender, recipients, themsg)
smtp.close()
With this function, you can just do:
send_file_zipped('result.txt', ['[email protected]'])
You're welcome.
nosklo
2008-10-04 00:17:28
That's one hell of an answer.
Jeremy Banks
2008-10-04 00:51:59
What if the questioner left off the homework tag?
S.Lott
2008-10-04 01:11:02
Since you got into the trouble of answering, edit your answer to add a directory tree in the zip, not just a single file.
ΤΖΩΤΖΙΟΥ
2008-10-04 09:40:51
Thank you very much. It wasn't a homework. I'm a php programmer who's trying to switch to Python. Your answer helped me a lot.
Boolean
2008-10-04 16:03:48
to get your sample working I had to remove the line smtp.connect() as it was giving me socket.error: [Errno 10061] No connection could be made because the target machine actively refused it.
Bryce Thomas
2009-11-14 15:02:37
@Bryce Thomas: That's probably because you don't have a SMTP server running on your machine. In mine it works fine.
nosklo
2009-11-15 12:24:05