How to Automate Email Sending with Python: Step-by-Step Guide
Sending personalized emails to multiple recipients can be a time-consuming and tedious task, especially when you have a long list of contacts. However, with a few lines of Python code and an email template, this process can be automated efficiently.
In this article, we will explore how to streamline your email outreach by leveraging the power of Python. Let's dive into the steps to make this automation a reality.
Getting started
Before we begin, ensure you have Python installed on your system. If not, you can download Python from python.org.
Prerequisite: Setting Up the SMTP Server
To send automated emails, you'll need an SMTP server. This article will guide you through setting up Gmail’s SMTP server, which is free to use. If you already have access to another SMTP server, you can use that as well.
Step 1: Navigate to Google Account
Open chrome browser and click on your profile icon, then click on ‘Manage your Google Account’. You will be navigated to your Google Account page.
Step 2: Navigate to App passwords
Now you need to turn on 2-step verification if it’s not already turned on. You can find it under the ‘Security’ tab in your Google Account. After turning on 2-step verification, search for ‘App Passwords’ in the search bar as shown in the image below and click enter.
After clicking enter, you will be navigated to this page. You may need to type google account password before entering this page for authentication purposes.
Step 3: Create New App
Now, you need to type your app name and click on create.
Step 4: Copy and Store the Generated Password
Google will generate a password for this app. Copy it and click on ‘Done’. Store the key somewhere safe because it will not be visible after this and if you fail to store it, you may need to create another app.
Implementing Email Automation with Python
Now that we have the prerequisites set up, let's start coding our email automation script in Python.
Step 1: Import Necessary Libraries
First, we'll import the libraries we need. The 'smtplib' and 'email' libraries are part of Python's standard library, so you don't need to install them separately. However, 'jinja2' is not included by default and must be installed.
To install 'jinja2', run:
pip install jinja2
Then, we can import the necessary libraries:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
fromjinja2importTemplate
领英推荐
Step 2: Define Constant Variable
In this step, you need to store your email address used to create the SMTP server, the generated password, recipients' emails and names, and the path of the email template. You can find the email template and code in my GitHub repository, which I added as a reference repository in this article (see the conclusion).
# Email credentials and server configuration
email = '[email protected]'? # Your SMTP email address
password = 'your-smtp-password'? # Your SMTP password
# List of recipient email addresses
recipients = [
????{'email': '[email protected]', 'name': 'Alan'},
????{'email': '[email protected]', 'name': 'Nanesh'},
????{'email': '[email protected]', 'name': 'Sanal'},
????{'email': '[email protected]', 'name': 'Adil'},
????{'email': '[email protected]', 'name': 'Savad'}
]
# Path to email template
EMAIL_TEMPLATE='automation_103/email_content.html'
Step 3: Write a Function to Read Email Template
We will use this function to read and return the contents of the email template.
# Load the email template
def load_email_template(path):
????try:
????????with open(path, 'r') as f:
????????????return f.read()
????except Exception as e:
????????print(f'Failed to read file: {e}')
Step 4: Setup the SMTP Server
In this code, We are initializing an SMTP server. I’m using 'smtp.gmail.com' as my host name and port number as '587'. If you're using a different SMTP server then you need to use that server's host name and port number in this section.
# Set up the SMTP server
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.starttls()
smtp.login(email, password)
Step 5: Get Email Template
Next, we load the email content using the 'load_email_template' function. This function returns the template as a string. If the template fails to load, an exception is raised to prevent further execution. Once the template is successfully loaded, it is converted into a Jinja2 'Template' object, which will allow us to dynamically generate the email content by rendering it with specific data.
# Load email content
template_str = load_email_template(EMAIL_TEMPLATE)
if not template_str:
????raise Exception('Failed to load email content.')
template=Template(template_str)
Step 6: Loop Through Recipients and Create Emails
We start by looping through each recipient in our list. For each recipient, we extract their name and email address.
for recipient in recipients:
????name = recipient['name']
????recipient_email = recipient['email']
Step 7: Setup Sender, Recipient, and Subject of the Email
For each recipient, we create a new email message. We use the 'MIMEMultipart' class to create an email with multiple parts, and set the sender, recipient, and subject of the email.
# Create the email
msg = MIMEMultipart('alternative')
msg['From'] = formataddr(('Your Name', email))
msg['To'] = recipient_email
msg['Subject'] = "My Email Subject"
Step 8: Render HTML Content
We use the Jinja2 template to render the email content, replacing placeholders with the recipient's name. This personalized HTML content is then attached to the email message.
# Render HTML content with recipient full name
html_content = template.render(name=name)
msg.attach(MIMEText(html_content, 'html'))
Step 9: Send the Email
We send the email to the recipient using the SMTP server.
# Send the email
smtp.sendmail(email, recipient_email, msg.as_string())
Step 10: Finalize and Quit the SMTP Server
After all emails are sent, we quit the SMTP server and print a confirmation message.
# Quit the SMTP server
smtp.quit()
print('Emails sent successfully.')
Conclusion
Automating email sending with Python streamlines your communication process, making it efficient and personalized. By setting up an SMTP server, using Jinja2 templates, and leveraging Python's email capabilities, you can save time and enhance your outreach efforts.
For the complete code and email template, check out my GitHub repository. Explore, clone, and customize the project to fit your needs. Feel free to reach out if you have any questions or need further assistance. Happy coding!