Introduction
In this digital era, everyone is familiar with email more or less. Email is a popular way to send any application, official text messages, documents, etc., everywhere.
Normally, we send emails manually. But you may have heard that we can do the same task with the help of automation.
In this tutorial, I will show, how you can send your emails using python programs. We will try to send text, and non-text emails also with attachments.
Our favorite python language offers a module called smtplib that allows us to send mail to any machine connected to the internet using SMTP or ESMTP listener daemon.
I have described every single information about "how to?". You just need to follow one-by-one thoroughly.
👉Visit Also: Create a Time Wasting Websites Blocker using Python
What is SMTP?
SMTP(simple mail transfer protocol) is a protocol used for the transmission of electronic mail(email) across the internet. It's a program used to send emails to another computer user based on the email address.
SMTP implies how an email message is formatted, encrypted, and relayed between two mail servers. These all are technical details. I'm not going deep over these topics. If You want to know more about how SMTP works, please visit this site.
Do we need to install smtplib?
Nop; by-default smtplib module comes with the python package. So, we don't need to install it extra.
Make sure you've done this task
👉Create a temporary Gmail account for testing purposes.
👉Go to "Manage your Google Account" then "Security"(See the steps have shown in the image below)
👉Make sure You don't have turned on the "2-Step Verification" option.
👉Now Turn on Less secure app access. Otherwise, the code will give you an error like this,
"smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials s23sm10991325pfh.146 - gsmtp')"
Important Note |
---|
If you see that less secure app section is missing in your google account manage section, make sure you've turned off the 2-step verification option. |
Sending a simple text email
First, we'll try to send an email containing only simple text.
Code
Output
Let's understand the above code
Connect to an SMTP server
Here, we're creating an SMTP object and connecting our machine to the mail server through smtplib.SMTP().
The domain name of the mail server is almost the same as the name of your email service provider. For example, here we've used Gmail's SMTP server at "smtp.gmail.com" and port number 587. This number is an integer value and will almost always be 587, which is used by TLS.
If the smtplib.SMTP() call is not successful, the mail server will not support TLS on port 587. In that case, you need to create an SMTP object like this,
Here, the port number will be 465 and the calling function will smtplib.SMTP_SSL().
Mail Servers
Here are some popular examples of email providers and their corresponding domain names. You can use other mail servers also instead of using Gmail. Find the way from here.
Email Provider | SMTP server domain name |
---|---|
Gmail | smtp.gmail.com |
Outlook.com/Hotmail.com | smtp-mail.outlook.com |
Yahoo Mail | smtp.mail.yahoo.com |
Comcast | smtp.comcast.net |
AT&T | smpt.mail.att.net (port 465) |
Verizon | smtp.verizon.net (port 465) |
Send the SMTP "Hello" message
ehlo() method is used to say hello to the SMTP mail server. It seems a weird name but is important for establishing an SMTP connection.
This function returns a tuple like this,
(250, b'smtp.gmail.com at your service, [2409:4060:2d88:a09a:f428:2dbe:69a4:dbf9]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8')
The first item in the returned tuple is 250. It represents the code for "success".
TLS Encryption
If you use the TLS encryption method on port 587, you will need to call starttls() to enable encryption of your connection.
If you use SSL encryption on port 465, skip this step. Because in that case the encryption is set up beforehand.
The value 220 in the returned tuple tells the mail server is ready.
Logging in to the SMTP server
After setting up your encrypted connection on the SMTP server, you can log in with your username and password.
Enter your username in "your_email@gmail.com" and password in "Your_Password". Return value 235 means your authentication has been successful.
Important Note |
---|
If you enter an incorrect password, the program will raise the "smtp.SMTPAuthenticationError" error. |
Sending the email
sendmail() method takes three arguments.
-> sender's email address,
-> receiver's email address, and
-> the email body or the message as a string.
If the email is successfully sent to all recipients, the sendmail() method returns an empty dictionary(see yellow line).
For the else case, there will be a key pair in the dictionary for each recipient for whom email delivery failed.
Disconnect from the SMTP server
It is important to disconnect your program from the SMTP server after sending the email. We do this by calling the quit() method.
Return value 221 means the session is ending.
Send an Email to multiple recipients
We have successfully sent an email to a single recipient. But sometimes it's required to send a single mail to multiple users. Doing so individually is a time-consuming task. Although Email service providers give options to select multiple recipients at a time.
In this section, we will perform the same task but using programming. We'll send a single email to multiple users using a python program.
The code would be almost the same as the previous but with minor changes. Here we will store the recipients' mail id in a python list. Later, we will pass that list as the second argument to the sendmail() method.
Code
Output
Sending HTML content in an email
So far we've only sent text-based emails. But if you check your mailbox, you can find some emails with formatted text. For example, with a title, bold and italic words, multiple images and hyperlinks, etc.
These things enrich an email content so it looks more professional. These are HTML and text combined emails called MIME(Multipurpose Internet Mail Extensions) Multipart email.
In Python, email.mime module handles these MIME messages(single or multiple text or non-text content).
Here, we will try to send an email with HTML contents; for example, multiple heading types(h1, h2, h3, h4), paragraphs, and hyperlinks.
First, you have to create an object of MIMEMultipart class; next, we need to mention its various features, like the subject of the email, sender and receiver's information, etc. The rest of the code is pretty straightforward. I hope you can grab the objectives of each line easily.
Code
Output
Sending an email with an attachment using python
When mailing to someone, sometimes we needed to provide attachments as well. In the offline mode we call it a parcel and drop it to the nearest post office or mailbox. The reason I'm talking about it is, we can add multiple attachments to an email content too.
Here, the attachments would be multimedia files, documents, etc.
The smtplib module offers a feature for adding attachments to an email. Email servers are designed to work with text data only; So how do you add attachment files there?
First, you need to read the byte streams, then encode that attachment using the base64 system.
Don't worry it's pretty straightforward. Simply follow these simple steps below.
👉 Open the file in the binary mode that you want to attach.
👉 Read the byte stream, encode them, and add a header with the file name.
Code
Output
👉Visit Also: Check the strength of your password using python - with regex
Summary
With advanced technology and programming, we can now automate many time-consuming tasks in this busy world. In this tutorial, we learned to automate such a task with the help of python programming.
We learned how to send email using python program. Python offers a module called smtplib and here we have taken the advantage of it.
We had to choose an SMTP server before sending emails using python. So I chose Gmail's SMTP server(smtp.gmail.com) to make it easier to understand.
An email may consist of text and non-text content. It can also contain documents, multimedia files, HTML content, etc. Throughout this tutorial, I have explained each of those in different examples.
These were basic knowledge for sending an email using Python but can help you add this great feature to an automation project for performing real-life tasks.
I hope you enjoyed this tutorial. Be sure to leave your comment below for any query. You'll get an immediate response.
Thanks for reading!💙
PySeek