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 smtplib


def 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 MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import smtplib


def 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

Capturing Query Parameters of request.get in Django

In Django, the request object contains a variety of information about the current HTTP request, including the query parameters. Query parameters are a way to pass additional information in the URL and are used to filter or sort data. The request object p…
Read more →

2 min read

Understanding related_name in Django Models

In Django, related_name is an attribute that can be used to specify the name of the reverse relation from the related model back to the model that defines the relation. It is used to specify the name of the attribute that will be used to access the relat…
Read more →

2 min read