Using Python to Send Email to Multiple Recipients – Introduction
Looking for ways to automate your emails? This post has complete code in Python to send email to multiple recipients.
Sending emails is still one of the best ways to stay connected with your customers while informing and educating them about your products and services. According to statistics, email marketing helps acquire customers 40x more than X and Meta combined.
However, if your customer base is large, sending emails manually to each one of your customers can be hugely time-consuming and difficult. Enter email automation. Automating emails lets you send targeted emails to multiple recipients and saves time and effort in the process. Python is one of the best Programming languages for email automation.
Table of Contents
How to Send Emails to Multiple Recipients Using Python?
To send emails in Python, there are primarily two ways:
1. Sending Email via SMTP
Simple Mail Transfer Protocol (SMTP) is an app-level protocol you can use to send an email. It determines how you can encrypt, format, and send emails between two mail servers.
Sending emails via SMTP is easy in Python as the programming language provides an in-built module to enable the process. This process is cost-friendly, thus, teams of different shapes and sizes can adopt it. Like HTTP manages app data, SMTP manages email traffic. However, email send times can be longer in this process and might involve long-term maintenance. So, some users also find it less secure.
To simplify this process, there’s “smtplib”, a library that Python provides to interact with SMTP. This library communicates with mail servers and makes sending emails effortless using your applications. For SMTP, smtplib uses the RFC 821 protocol.
Let’s understand how to set up smtplib and use its features to send emails.
But before you start, ensure:
- You have installed Python in your system.
- Have an accessible email account ready.
Step #1: Import the required libraries
Import smtplib
from email.mime.text import MIMEText
While the smtplib enables you to establish a collection with the email server, MIMEText enables emailing. It takes three arguments – email content, sender, and receiver.
Step #2: Create an SMTP object
smtpObj = smtplib.SMTP( [host [, port]] )
Let’s understand what each element means in the above code:
- host: It’s the name of the host running the SMTP server. If the SMTP runs on your local system, you can specify the name – localhost.
- port: It’s the port number that you will need to specify.
Step #3: Secure your connection using TLS or SSL
Encrypting an SMTP connection is vital to prevent hackers from accessing your emails. For SSL, we use port 465, and for TLS, the port number is 587. We’re using TLS here – .starttls().
SMTP offers an instance – sendmail() to send an email message. It includes three parameters:
- receiver – It contains several strings; each string points to one recipient’s address.
- sender – It contains a string with the sender’s address.
- message – Strings formatted as per RFCs specifications.
Here’s how it looks:
smtpObj.sendmail(sender, receivers, message)
Step #4: SMTP Code to send email to multiple recipients
Let’s see the complete code to send emails in Python using SMTP. Here, we will use Mailtrap SMTP.
Import smtplib
from email.mime.text import MIMEText
# Set up configuration
# Adding TLS port number
port = 587
smtp_server = “live.smtp.mailtrap.io”
# Login by SMTP service provider
login = “api”
# Password by the SMTP service provider
password = “Thisispassword12345”
email_ sender = [email protected]
email_receivers = [“[email protected]”, “[email protected]”, “[email protected]”]
text = “””\
Hello XYZ,
Thanks for subscribing to this newsletter!
Get tips and tricks to start an online business in 2024. If you found it helpful, share it with your friends and family 🙂
“””
email_message = MIMEText(text, “plain”)
email_message[“Subject”] = “Email to multiple recipients”
email_message[“From”] = email_sender
email_message[“To] = “,”.join(email_receivers)
with smtplib.SMTP(smtp_server, port) as server:
server.starttls()
server.login(login_id, login_password)
# Include each receiver in the loop and send emails individually
for receiver in email_receivers:
server.sendmail(email_sender,receiver,email_message.as_string() )
print(‘Sent’)
2. Send Email via an API
Another way to send emails is to use third-party email APIs such as Mailtrap’s Python SDK. These email services offer high delivery speeds, robust features like comprehensive dashboards and analytics, and improved security. However, this process also has certain limitations, such as dependency on the third-party API provider and a learning curve.
Step #1: Set up the environment
First, ensure that you have connected and verified your domain with an email delivery service like Mailtrap. If not, verify the domain. In addition, ensure you have Python installed in your system. Once done, install Mailtrap’s Python SDK or any other email API you wish to use.
- For sending a text-only email, import “Mail”, “EmailAddress”, and “EmailAPIClient” classes.
- Remember, we use an API key to authenticate the EmailAPIClient instance.
Step #2: API Code to send email to multiple recipients
Here’s how to send a plain-text email using an email API:
from emailAPI import Mail, EmailAddress, EmailAPIClient
# Example of email APIs are Mailtrap or SendGrid
# Create the Mail object for multiple recipients
newmail = Mail()
# Define sender address and name
sender1=Address(email= “[email protected]”, name=“Sender”),
to = [
Address(email=“ [email protected]”, name=“ABC”)
Address(email=“ [email protected]”, name=“XYZ”)
],
subject=“This is subject”,
text=“Hello, /nThis is a sample plain-text email for multiple recipients.”
# Define EmailAPIClient using your API keys
newclient = EmailAPIClient(APIkeys=“email_api_key”)
# Use the send method to send your email
newclient.send(newmail)
print(“Congratulations! You sent email to multiple recipients.”)
Final Thoughts
With this guide, you can use Python to send emails to multiple recipients. Furthermore, get the best results by referring to Python documentation and experimenting with different code and email scenarios. You can also build some email-sending functionalities using Python frameworks like Dash and Plotly for adding reports and graphs, Marrow Mailer for adding configurations, and Django for creating HTML templates.
Frequently Asked Questions (FAQs)
Q.1 Can Python send automatic emails?
Answer: Yes, you can send automatic emails in Python using in-built libraries like “smtplib” and third-party APIs.
Q.2 What is the best language for email automation?
Answer: Some of the best languages for email automation are Python, JavaScript, Java, Swift, and Kotlin. They all offer a rich set of libraries, features, and functionality.
Q.3 Can I use Gmail to send automatic emails?
Answer: Yes, it is possible to use Gmail to send automatic emails. Do this by utilizing the “Canned Responses” functionality with Google Sheets and filters.
Recommended Articles
We hope this guide helped you to use Python to send email to multiple recipients. For more Python or email related articles check these resources.