Everybody gets promotional emails from companies like Amazon and Swiggy, urging them to check out their flash sales or new dish.
Ever ponder how companies send emails to millions of recipients? It is not possible to complete by hand! Instead, they effectively manage and schedule their emails using automated email systems.
The best thing is that open-source Python packages allow you to quickly build it. Let's say you are a professional looking for a new job or a student. It can take a lot of time and be prone to error to manually send your cover letter and resume to several recruiters.
In this post, I'll walk through the process of using code to automate the distribution of job applications using the Python library.
Prerequisites
Before we dive into the process of automating email systems with Python, make sure you have a basic working knowledge of general Python concepts.
If you’re new to Python, you can check out the Introduction to Python course on Hyperskill, where I contribute as an expert.
Step 1: Set Up the Connection to Your Email Server
A built-in Python package is called Smtplib. You can send emails using any service, including Gmail, Yahoo, and others, and it's free to use. In this example, I'll use Gmail.
Depending on the server you select, the port number will vary. With the server and port entered as input parameters, we can establish a connection by using the smtplib.SMTP class included in the package. Simple Mail Transfer Protocol is referred to as SMTP.
import smtplib
my_email=’jess_xxx@gmail.com’
password_key=’xxxxx’
# SMTP Server and port no for GMAIL.com
gmail_server= "smtp.gmail.com"
gmail_port= 587
# Starting connection
my_server = smtplib.SMTP(gmail_server, gmail_port)
my_server.ehlo()
my_server.starttls()
# Login with your email and password
my_server.login(my_email, password_key)
Next, we invoke the extended hello method, or ehlo(), to identify the client to the server. Making sure there is no information leakage and that your connection is secure is also very important.
By using the starttls() function, we can use Transport Layer Security (TLS) to encrypt the connection. Following that, you can use your email address and password to log in using the login() method.
Step 2: Add Different Types of Content Using MIME
Your connection is prepared! But first, it's important to know how to attach various kinds of content to your email before we look at how to send emails to a list of recipients.
If your email is a text message, you can send it straight to your SMTP server. What happens, though, if you want to include a PDF of your grade report or resume or a link to your LinkedIn profile?
Insert MIMEMultipart here. Multipurpose Internet Mail Extensions is what MIME stands for. It also goes by the name Multipart and is compatible with HTML and plain text. You have more formatting options and the ability to attach images when you add content using HTML.
The MIMEMultipart module provides a class for creating MIME documents representing a multipart message. It can include text, images, and attachments.
Let’s create a MIMEMultipart object named message, as shown below. We use the alternative subtype, which includes plain text and HTML versions of the message.
from email.mime.multipart import MIMEMultipart
message = MIMEMultipart("alternative")
How to add text content:
The MIMEText module provides a class for creating MIME documents representing plain text in an email message.
from email.mime.text import MIMEText
text_content= “ Hello, I am a final year student with an Mtech degree in Computer science specializing in Artificial Intelligence. I’m interested in data science roles at your organization.”
message.attach(MIMEText(text))
How to add images to your email:
The MIMEImage module provides a class for creating MIME documents representing image data in an email message.
Import the MIMEImage module and define the path that has your image file. Here, we read its binary data and attach it to the message object as a MIMEImage part.
from email.mime.image import MIMEImage
import os
# define your location
grade_card_path = 'path/to/your/grade_card.jpg'
# Read the image from location
grade_card_img = open(grade_card, 'rb').read()
# Attach your image
message.attach(MIMEImage(grade_card_img, name=os.path.basename(grade_card_path)))
How to attach files to your email:
A class for creating MIME documents that represent any binary data in an email message is provided by the MIMEApplication module. Attaching files is one of its frequent uses.
To attach an attachment file (resume_file) to the message object as a MIMEApplication part, first define its path, read its binary data, and attach it. Additionally, the filename is specified in the Content-Disposition header.
resume_file = '...../resume.txt'
# Read the file from location
with open(resume_file, 'rb') as f:
file = MIMEApplication(
f.read(),
name=os.path.basename(resume_file)
)
file['Content-Disposition'] = f'attachment;
filename="{os.path.basename(resume_file)}"'
message.attach(file)
When attaching files, replace the placeholder paths with the actual ones. You can also attach a list of files using this function.
Step 3: Send Multiple Customized Emails
I'm assuming you know how to include various kinds of content in emails. Let's get ready and begin our project: sending recruiters individualized emails automatically.
It is crucial to tailor an automation system to meet particular requirements when developing it. If you are a recruiter, for example, you will want an email that is customized for your company and yourself rather than one that just calls you "Sir" or "Madam."
You'll add customized fields that take in input parameters to your text message in order to accomplish this.
Make a CSV file and insert the data you wish to customize into distinct columns. For instance, I've made a CSV file containing the job role, organization name, recruiter email, and recruiter name.
Save the job_contacts.csv CSV file. To prevent formatting problems, make sure there are no whitespaces and that a comma separates the values. Use the str.format() function to add customized content to a text message. For the parts you want to customize, curly-bracket placeholders can be used.
Look at my example:
text_content= """Hello {recruiter_name}, I hope you are doing well. I’m Jane Doe, an engineering graduate with an Mtech in Computer Science and a specialization in Artificial Intelligence.I am writing to inquire regarding open roles in {job_role} at {organization}. I have experience performing data analysis and modeling through my internships and research projects. I’m excited to have an opportunity to apply my skills and learn more in the {organization_sector}.I have attached my grade card and résumé below. Looking forward to hearing from you.Thanks,…… """
This brings us to the last section. As seen in the sample below, we read the CSV file and loop through each row. Every time a new job detail is added, it is reviewed, updated, and an email is sent to the recruiter.
import csv
with open("job_contacts.csv") as csv_file:
jobs = csv.reader(csv_file)
next(jobs) # Skip header row
for recruiter_name, recruiter_email, organization,
organization_sector,job_role in jobs:
email_text=text_content.format(recruiter_name, recruiter_email
Organziation, organization_sector, job_role)
# Attaching the personalized text to our message
message.attach(MIMEText(email_text))
my_server.sendmail(
from_addr= my_email,
to_addrs=recruiter_email,
msg=message
)
my_server.quit()
Finally, we use SMTP’s sendmail() function with the from and to email addresses and messages as input. Don’t forget to quit the server once the process is complete.
Tips & Best Practices
I hope you enjoyed the project. You can use this template to create an automated email system for diverse purposes like marketing campaigns, promoting your newsletter, and more.
Here are a few recommendations to remember:
- You shouldn't store your email password in the code. Instead, prompt it through input or store it as an environment variable.
- You can create a secured SMTP connection with SSL (Secure Sockets Layer). It is an alternative to TLS we have used to provide encryption on an insecure connection.
- You can create multiple personalized email messages for different job sectors and use the most fitting one using a switch-case match.
- Thank you for reading! I'm Jess, and I'm an expert at Hyperskill. You can check out an Introduction to Python course on the platform.