Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

Sending Email With Zip Files Using Python

3 min read

In this tutorial, we will learn how to send emails with zip files using Python's built-in modules.

Pre-Requirements

I am assuming that you already have an SMTP (Simple Mail Transfer Protocol ) server setup if not you can use Gmail SMTP or something like mailgun. A simple google search will land you on multiple ways to get free SMTP servers.

Sending Zip File in an Email with Python

from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText

import smtplibdef send_mail():
    # Create a multipart message
    msg = MIMEMultipart()
    body_part = MIMEText(MESSAGE_BODY, 'plain')
    msg['Subject'] = EMAIL_SUBJECT
    msg['From'] = EMAIL_FROM
    msg['To'] = EMAIL_TO
    # Add body to email
    msg.attach(body_part)
    # open and read the file in binary
    with open(PATH_TO_ZIP_FILE,'rb') as file:
    # Attach the file with filename to the email
        msg.attach(MIMEApplication(file.read(), Name='filename.zip'))
    # Create SMTP object    smtp_obj = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    # Login to the server    smtp_obj.login(SMTP_USERNAME, SMTP_PASSWORD)
    # Convert the message to a string and send it
    smtp_obj.sendmail(msg['From'], msg['To'], msg.as_string())
    smtp_obj.quit()

Variables:

  • EMAIL_SUBJECT = Subject of the email
  • EMAIL_FROM =Receiver's email address
  • EMAIL_TO = Senders email address
  • MESSAGE_BODY = Email body
  • PATH_TO_ZIP_FILE = Path to the zip file
  • FILE_NAME = Filename for the email attachment
  • SMTP_SERVER = SMTP server
  • SMTP_PORT = SMTP port
  • SMTP_USERNAME = Username for SMTP
  • SMTP_PASSWORD = SMTP password

Since these variables include sensitive data I always recommend feeding this data from environment variables however you can also pass them as arguments to the function.

Explanation

First, the function creates a multipart message object. MIME (Multipurpose Internet Mail Extensions) Multipart is used when a mail has multiple messages or content having different content types such as Text, Image, HTML, or a file.

The MIMEMultipart object accepts parameters in key-value pares therefore we sent the necessary mail parameters such as sender address, receiver address, and subject in the same manner.

Next, we attached the message body to the email you can also attach HTML here depending on your need.

Then we opened the zip file from our system in binary because the transmission of data is done in the octet binary stream. Then using the MIMEApplication method we are attaching the binary zip file with a filename.

Now we are done with the email body next we need to configure the SMTP to deliver the mail.

Python comes with the built-in smtplib module for sending emails using the Simple Mail Transfer Protocol (SMTP).

For sending mails first we need to create an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon taking the necessary arguments and login credentials and finally, at the end, we convert the message into a string and send it using the sendmail method.

Sending Multiple Zip Files in an Email Using Python

from email.mime.multipart 
import MIMEMultipartfrom email.mime.application 
import MIMEApplicationfrom email.mime.text 
import MIMETextimport smtplibdef 

send_mail():
    # Create a multipart message
    msg = MIMEMultipart()
    body_part = MIMEText(MESSAGE_BODY, 'plain')
    msg['Subject'] = EMAIL_SUBJECT
    msg['From'] = EMAIL_FROM
    msg['To'] = EMAIL_TO
    # Add body to email
    msg.attach(body_part)
    #Make a list of files
    files = [FILE_1_path,FILE_2_PATH]
    #Loop over the files and attach them to email body
    for file in files:
        # open and read the file in binary
        with open(file,'rb') as file:
        # Attach the file with filename to the email
            msg.attach(MIMEApplication(file.read(), Name=file.name))
    # Create SMTP object
    smtp_obj = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    # Login to the server
    smtp_obj.login(SMTP_USERNAME, SMTP_PASSWORD)
    # Convert the message to a string and send it
    smtp_obj.sendmail(msg['From'], msg['To'], msg.as_string())
    smtp_obj.quit()

Almost similar to the last one however here we created a list of files and looped over them then attached it to email body.


PROGRAMS

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read