How can I compress a folder and email the compressed file in Python?

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()

    """
    # alternative to the above 4 lines if you're using gmail
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.login("username", "password")
    server.sendmail(sender,recipients,themsg)
    server.quit()
    """

With this function, you can just do:

send_file_zipped('result.txt', ['[email protected]'])

You're welcome.

Tags:

Python