Email Automation with Python. Automate emails with attachments in... | by Conner Leavitt | Towards Data Science

When I first started using python I saw it as an upgrade to excel. A tool I could use to improve my work in data analysis. The better I got at python the more streamlined my analysis became, and I started to realize python was more than a tool that allowed me to create stunning visuals or perform high function mathematics. I began to explore more of the capabilities of python and started to realize I was merely scratching the surface with this language and I could actually start automating a few of the processes. However, I was held up by the idea that I would be incapable of doing such things with the language because I would tell myself, “I am not a software engineer”. Well, I am here to tell you I am still not a python software engineer, but I can automate processes to make my analysis more effective and become a more valuable team player.
In order to start right, you need to have an end in mind. So, take me as an example: When I learned I wasn’t utilizing all of the programming language potentials I immediately began to think about how I could effectively incorporate these concepts into my work to become more productive. Then it hit me. Reporting. As an analyst, I am often asked to analyze and report. As a good analyst, I already have my data pipeline set up on a timer so I can bring the data in autonomously and I already have the script written and set up to create the tables, visuals, and desired stats on the subject. The reporting, on the other hand, was not... I still had to take my visuals and paste them into a presentation and then send the email to the appropriate individuals. Perfect. I have found an area in my work where it would be productive to try an automate. My end goal is: to create a pdf report, attach said report to an email and send the email all within python.
Here are the libraries and packages you will need to get your emails automated
#to create pdf reportfrom io import BytesIOfrom reportlab.pdfgen import canvasfrom django.http import HttpResponse#to automate emailimport email, smtplib, sslfrom email import encodersfrom email.mime.base import MIMEBasefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText
Now, you may not need every dependency I have listed above, but these are the ones I wanted to use for my project.
For this article, I am going to write up a simple example. I am going to create the pdf with “canvas” and add a few personalizations such as background-color, font and font size, a few text strings and an image (a chart)
The code
#name and create pdfc = canvas.Canvas('automate_report.pdf')#set background color (this color is yellow I do not recommend)c.setFillColorRGB(1,1,0)#Select font and font sizec.setFont('Helvetica', 30)#create two text strings and set there position on the pagec.drawString(5, 660,'Missing data chart for Titanic Data')c.drawString(5, 630, 'Report generated by Python')#add an image determine it's position and width and heightc.drawImage('Survival.png', 5,90,480,400)#show page and save itc.showPage()c.save()
Here we have our pdf.
Some things to note.
The image was in the same directory as this python scriptThis is just a basic outline. I suggest going to the documentation of canvas if you want to learn more about creating more sophisticated pdf reports
The image was in the same directory as this python script
This is just a basic outline. I suggest going to the documentation of canvas if you want to learn more about creating more sophisticated pdf reports
We have a pdf generated and just waiting to be sent through cyberspace, so let’s get it on its way!
before we dive into the code you might want to make a burner email account so that you can test the email on your own email rather than a friend’s email.
Pro tip: make sure the password is easy to remember.
# assign key email aspects to variables for easier future editingsubject = "Weekly Report"body = "This is an email with the desired report attached"sender_email = "connerleavitt@gmail.com"receiver_email = "connerleavitt@icloud.com"file = "automate_report.pdf" # in the same directory as scriptpassword = "abc123"# Create the email head (sender, receiver, and subject)email = MIMEMultipart()email["From"] = sender_emailemail["To"] = receiver_email email["Subject"] = subject# Add body and attachment to emailemail.attach(MIMEText(body, "plain"))attach_file = open(file, "rb") # open the filereport = MIMEBase("application", "octate-stream")report.set_payload((attach_file).read())encoders.encode_base64(report)#add report header with the file namereport.add_header("Content-Decomposition", "attachment", filename = file)email.attach(report)#Create SMTP session for sending the mailsession = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with portsession.starttls() #enable securitysession.login(sender_email, password) #login with mail_id and passwordtext = email.as_string()session.sendmail(sender_email, receiver_email, text)session.quit()print('Mail Sent')
Now the comments should be able to help your understanding of how all the code works and interacts with one another. As a personal preference, I like to set a lot of what you would usually hard code into the script to a variable so that it is easier to edit if need be.
The major take away from this article is that anything is possible with python and the resources exist to help you achieve what you previously thought was impossible. Python is a wonderful tool to help make you more productive and efficient so take advantage of it!