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 Emails With CSV Attachment Using Python

3 min read

Sending emails with attachments is a common task in many applications. It allows you to share data and documents easily. In this article, we'll explore how to send emails with CSV file attachments using Python.

In this tutorial, we will learn how to send emails with CSV attachments using Python.

Introduction

CSV (Comma-Separated Values) is a popular format for storing tabular data. It's widely used for spreadsheets, databases, and data interchange. Sending CSV attachments via email can be particularly useful for sharing reports, data exports, or any other structured information.

We'll use the built-in smtplib and email libraries in Python to accomplish this task.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  1. Python installed on your system.
  2. A valid email account with SMTP server details.

Sending Emails With CSV Attachment Using Python

from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMETextimport 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 CSV file in binary
    with open(PATH_TO_CSV_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()

Variables:

  • EMAIL_SUBJECT = Subject of the email
  • EMAIL_FROM =Receiver’s email address
  • EMAIL_TO = Senders email address
  • MESSAGE_BODY = Email body
  • PATH_TO_CSV_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 them from environment variables however you can also pass them as arguments to the send_mail function.

Explanation

First, we are importing all the necessary modules for the function then inside the function, we are creating a multipart message using MIMEMultipartobject. Since the multipart object takes arguments in key-value pairs therefore we are providing all the necessary arguments such as message body, sender's address, receiver address in the same manner.

Next, we are opening the CSV file in binary form and attaching the binary stream to the email using MIMEApplication method.

Then we are using Python's built-in SMTP module and creating an SMTP session object by providing the login credentials and finally sending the mail.

Note that in case you want to send multiple CSV files in the same mail you can create a list of files and loop over them and attach it to the email like this.

.....
# create file listcsv_files = ['path_to_csv_1','path_to_csv_2']
# loop over files
for file in csv_files:
    with open(file,'rb') as file:
    # Attach the file with filename to the email
        msg.attach(MIMEApplication(file.read(), Name=FILE_NAME)).....

Conclusion

Sending emails with CSV attachments using Python is a straightforward process. The smtplib and email libraries provide the necessary tools to compose and send emails with attachments. Whether you need to share reports, data exports, or any other structured information, this approach allows you to automate the process and enhance communication with your recipients.


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