2 min read
In this tutorial, we will learn how to send emails with CSV attachments using Python.
I am assuming you already have an SMTP server setup if not you can use the Gmail SMTP or Maligun or anything similar to that.
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 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()
EMAIL_SUBJECT
= Subject of the emailEMAIL_FROM
=Receiver’s email addressEMAIL_TO
= Senders email addressMESSAGE_BODY
= Email bodyPATH_TO_CSV_FILE
= Path to the zip fileFILE_NAME
= Filename for the email attachmentSMTP_SERVER
= SMTP serverSMTP_PORT
= SMTP portSMTP_USERNAME
= Username for SMTPSMTP_PASSWORD
= SMTP passwordSince 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.
First, we are importing all the necessary modules for the function then inside the function, we are creating a multipart message using MIMEMultipart
object. 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 list
csv_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))
.....
PROGRAMS
Latest from djangocentral
2 min read
2 min read