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

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?

Asked by: Julian412 | Posted: 01-10-2021

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='you@you.com'):
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')
encoders.encode_base64(msg)
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.sendmail(sender,recipients,themsg)
server.quit()
"""


With this function, you can just do:

send_file_zipped('result.txt', ['me@me.org'])


You're welcome.

Answered by: Andrew368 | Posted: 02-11-2021

Look at zipfile for compressing a folder and it's subfolders.

Look at smtplib for an email client.

Answered by: Julia590 | Posted: 02-11-2021

You can use zipfile that ships with python, and here you can find an example of sending an email with attachments with the standard smtplib

Answered by: Ned406 | Posted: 02-11-2021

# Similar questions

python - How to compress and save the compressed image in mongodb using mongo engine

I got the below code from stack is there anyone who can help to save the compressed image in mongodb using mongoengine &gt;&gt;&gt; from PIL import Image # My image is a 200x374 jpeg that is 102kb large &gt;&gt;&gt; foo = Image.open("path\\to\\image.jpg") &gt;&gt;&gt; foo.size (200,374) # I downsize the image with an ANTIALIAS filter (gives the highest quality) &gt;&gt;&gt; foo = foo.resize((160,300...

python - Compressed xml on soappy

I'm developing an application that uses webservices in python, both sides (server and client) are developed in Python and uses SOAPpy for the webservices, but, you know, the xml is too verbose, I want to compress it, but as far as I have searched in google I can't find something helpful.

I need to come up with a file format for new application I am writing. This file will need to hold a bunch other text files which are mostly text but can be other formats as well. Naturally, a compressed tar file seems to fit the bill. The problem is that I want to be able to retrieve some data from the file very quickly and getting just a particular file from a tar.gz file seems to take longer than it should. I am assume...

python - How to tell if a file is gzip compressed?

I have a Python program which is going to take text files as input. However, some of these files may be gzip compressed. Is there a cross-platform, usable from Python way to determine if a file is gzip compressed or not? Is the following reliable or could an ordinary text file 'accidentally' look gzip-like enough for me to get false positives? try: gzip.GzipFile(filename, 'r') # ...

Import compressed SQL dump into Postgresql with python

I have to import a compressed sql dump into a PostgreSQL database. The dump gets created by: pg_dump -F c So I get a compressed file, which I can't just parse line by line and then use psycopg2 to upload it into my database. The compressed dumps I'm dealing with are quite big (up to 10GB). What would be an efficient way to do import them?

python - how to detect quickly if a string is zlib compressed?

What's the quickest way in python to determine if a string was compressed by zlib. I am using this currently. def iscompressed(data): result = True try: s =zlib.decompress(data) except: result = False return result I am sure there is a more elegant way.

Reading zlib/gzip compressed data from MS SQL Server using Python

I'm using Python 2.6 to read data from SQL Server. I'm stuck because a column in my DB is varbinary. I'm using pyodbc, and the data type in the Python program is "buffer". Now, this column in the DB stores gzip compressed text. I'm unable to figure out how to decompress this from Python, given access to the 'buffer' data type. Any help/pointers please? This is what I'm doing con = py...

Python: create a compressed tar file for streamed writing

I need to produce the tar.gzipped text file. Is there a way to create a file for constant writing (to be able to do something like compressedFile.write("some text")), or do I need to create a raw text file first, and compress it aftewards? This will be quite unfortunate, as the file should be really long and well compressable.

python - urllib2 load part of compressed page

I need analogue: urllib2.urlopen(url).read(100) But for compressed pages, like: request = urllib2.Request(url) request.add_header('Accept-encoding', 'gzip') response = urllib2.urlopen(request) buf = StringIO(response.read(100)) gzip.GzipFile(fileobj=buf, mode='r').read() IOError: CRC check failed 0xd71b7369L != 0x0L

How to get a random line from within a gzip compressed file in python without reading it into memory

Let's say I have a 531 gig gzipped textfile with exactly 512 548 457 601 475 lines split by '\n' and wanted to get a random line out of it without filesplitting. (Don't worry, it's not really THAT large; just wanted to state that it's a huge file and I know how many lines it has.) How I would normally do it with a smaller compressed file: import fileinput import gzip import random list = [] for li...

sockets - How to decode the gzip compressed data returned in a HTTP Response in python?

I have created a client/server architecture in python, I take HTTP request from the client which is served by requesting another HTTP server through my code. When I get the response from the third server I am not able to decode the gzip compressed data, I first split the response data using \r\n as separation character which got me the data as the last item in the list then I tried decompressing it wi...