While commercial email clients offer the convenience of a user-friendly GUI, they often lack the flexibility and customizability that many developers or content creators desire for their emailing needs.
Be it for sending a thank you email to a new subscriber on your social media channel or adding email functionality to your latest project, the ability to send automated messages using SMTP in Python is something that is bound to come in handy.
Read on to find out how you can get a Python script to send emails running on your machine today.
What Is SMTP?
To put it simply, SMTP, or Simple Mail Transfer Protocol, is a communication protocol for mail servers to transmit email over the internet.
It’s an integral part of the application layer of the TCP/IP suite, which is a set of protocols used for communication over the internet or other similar networks. In a network where SMTP is implemented, a process known as store and forward helps move mail across networks.
At each endpoint, software known as Mail Transfer Agent (MTA) uses store and forward to facilitate communication between the participating SMTP servers. The main role of SMTP, therefore, is simply to dictate where and how mail moves from one point to another in a network.
Getting Started
You need to have an email account to use for sending emails using this program. This is because we will be using the email client’s SMTP service to send emails. For this tutorial, we’ll be using Gmail.
You can also use a local SMTP debugging server to send test emails, but for now we’ll use an email account to send emails since it’s more intuitive.
It is possible to simply use an existing Gmail account, but as you play around with your program, it may soon get filled up with test emails. This is why we recommend creating a ‘throwaway’ account for the purpose of testing.
Now, turn on the option to allow less secure apps to access your Gmail account. This is another reason to use a throwaway email as it’s not recommended to play around with the privacy settings of your primary email.
Writing the Email in Python
Python 3 comes pre-installed with a module called smtplib (short for smtp library), which can be used to work with SMTP servers.
Like any other Python module, the first thing you have to do is to import smtplib.
import smtplib
Initializing an SMTP Object
Now, you can use smtplib to create an SMTP object, which will provide you with most of the functionality of a conventional email client. However, an SMTP object’s functions can only be used via instance methods. So, naturally, the next step is to declare an object instance.
mySMTP = smtplib.SMTP("smtp.google.com")
This configures the SMTP object to send out emails using Google’s SMTP server.
After this, we specify the sender and recipient emails. Here is where the Gmail account you made earlier comes in handy.
emailSender = “[email protected]”
myThroaway = "[email protected]"
emailRecipients = [myThroaway]
One thing to note here is that the recipient list is actually an array, which means that it is designed to store non-atomic values. As a result, you can even specify an entire mailing list in this field!
Writing the Message
Arguably the most straightforward part of the process, here you have to input values that you’d normally add when composing a new email. This includes:
- Sender’s details
- Recipient’s details
- Subject
- Message body
These fields are put together inside triple-quotation marks and are demarcated as follows:
newEmail = """From: From Person
To: To Person
Subject: Email Test
This is the body of the email.
"""
Sending the Email
Finally, we can use the sendmail command to send the mail from your SMTP server to the recipient’s server.
mySMTP.sendmail(emailSender, emailRecipients, newEmail)
Now, there’s just one final step: re-organising the code to prevent any foreseeable program crashes.
Troubleshooting Your Python Email Program
Sometimes, your SMTP server may fail to establish a connection with that of the recipient, or there may be an issue with sending an email from one SMTP port to another. In such an event, your program might crash unexpectedly.
To account for such possibilities, you can use a try-except block and put the error-prone statements inside the try block. Your entire program, along with the try-except block, should look something like this:
import smtplib
emailSender = “[email protected]”
myThroaway = ‘[email protected]’
emailRecipients = [myThroaway]
newEmail = """From: From Person
To: To Person
Subject: Email Test
This is the body of the email.
"""
try:
smtpObj = smtplib.SMTP(‘smtp.gmail.com’)
mySMTP.sendmail(emailSender, emailRecipients, newEmail)
print (“Email sent successfully!”)
except SMTPException:
print ("Error: There was an error in sending your email.")
Securing Your Emails
If you intend to use Python in a real-world setting to send emails, it is important to make sure that the communication is secure on both ends.
Using a simple SMTP server with the default port does not provide any encryption layer to the communication. This means that if any third-party is listening in on your network, it can access your login credentials and the information contained in your email.
One way to circumvent this problem is to use the TLS (Transport Layer Security) protocol to encrypt your communication. This is the same protocol used by major email clients such as Gmail and Outlook to ensure that your emails never fall into the wrong hands.
To do so, we need to make a few minor changes to the program we created earlier.
The first step, of course, is to import the ssl library along with smtplib. The ssl library gives you the ability of creating a secure SSL context and communicating over an encrypted network by connecting to specific ports on both ends.
A secure SSL context is nothing but a collection of ciphers, protocol versions, trusted certificates, TLS options and TLS extensions.
Following this, we can specify the TLS port and add in a few ssl library functions to create a secure emailer.
The code, with all the changes made, looks something like this:
import smtplib, ssl
smtpServer = "smtp.gmail.com"
port = 587
myEmail = "[email protected]"
password = "my_password"
#email and password can also be user input fields
context = ssl.create_default_context()
newEmail = """From: From Person
To: To Person
Subject: Email Test
This is the body of the email.
"""
try:
server = smtplib.SMTP(smtpServer,port)
server.starttls(context=context)
server.login(newEmail, password)
except Exception as e:
print("the email could not be sent.")
finally:
server.quit()
As before, you should create and use the SMTP instance in a try-except block in order to prevent any abrupt program crashes.
What You Can Do With This Python Script
Now that you’ve picked up the awesome and surprisingly useful skill of automating emails using code, you can apply it to any platform that requires sending emails to a diverse mailing list.
From using it on your personal website to send automated acknowledgement emails to using it to email Christmas cards or invitations to your family and friends, the uses of this small Python script are limited only by your own creativity.
Also, this is just one of the many awesome things that you can do with Python. With its ubiquitous developer support and easy-to-learn syntax, picking up a Python skill has never been easier.
To continue building cool things with code, check out our guide on how to build your very own Telegram bot with Python 3!