Automate your email service - Sending emails using python

send email using smtplib module in python - PySeek

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 AlsoCreate 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')"

turn on the less secure app in your google account - PySeek
Turn on less secure app

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

# Sending a plain text email
import smtplib

# creating an object of SMTP class
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('your_email@gmail.com', 'Your_Password')
msg = 'Why You\'re putting my mail into spam box'
smtpObj.sendmail('your_mail@gmail.com','recipients@gmail.com',msg)
smtpObj.quit()

Output

sending only plain text email using python - PySeek

Let's understand the above code

Connect to an SMTP server

>>> smtpObj = smtplib.SMTP('smtp.gmail.com', 587)

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,

>>> smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465)

Here, the port number will be 465 and the calling function will smtplib.SMTP_SSL().

Mail Servers

at mail server. It is an at the rate sign

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

>>> smtpObj.ehlo()

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

>>> smtpObj.starttls()
(220, b'2.0.0 Ready to start TLS') 

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

>>> smtpObj.login('your_email@gmail.com', 'Your_Password')
(235, b'2.7.0 Accepted')

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

>>> msg = 'Why You\'re putting my mail into spam box'
>>> smtpObj.sendmail('sender@gmail.com', 'receiver@gmail.com', msg)
{}

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

>>> smtpObj.quit()
(221, b'2.0.0 closing connection s2sm17645923pfe.215 - gsmtp')

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

# Send an email to multiple recipients
import smtplib

# Email Server smtplib.smtp
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('your_email@gmail.com', 'Your_Password')

msg = 'Why You\'re putting my mail into spam box'
sender = 'your_email@gmail.com'
recipients = ['receiver1@gmail.com', 'receiver2@gmail.com']
# Send the message
smtpObj.sendmail(sender, recipients, msg)

smtpObj.quit()

Output

Send an email to multiple recipients using a python program

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

'''Sending an email with HTML messages'''
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

msg = MIMEMultipart()
msg["subject"] = "HTML Message"
msg["From"] = "your_mail@gmail.com"
msg["To"] = "recipient1@gmail.com, recipient2@gmail.com"
msg["Cc"] = "example@gmail.com"


html_text = """\
<html>
<body>
    <h1 style="text-align: left;">Sending Email Using Python</h1>
<h2 style="text-align: left;">Sending Email Using Python</h2>
<h3 style="text-align: left;">Sending Email Using Python</h3>
<h4 style="text-align: left;">Sending Email Using Python</h4>
<p style="text-align: left;">Sending Email Using Python</p>
<p style="text-align: left;">To know more information please
visit&nbsp;<a href="https://pyseek.blogspot.com/">PySeek</a>.
<br />
</p>
</body>
</html>
"""

# HTML Mimetext object
body = MIMEText(html_text, "html")

msg.attach(body)

smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('your_mail@gmail.com', 'Your_Password')

smtpObj.sendmail(msg["From"], msg["To"].split(","), msg.as_string())

smtpObj.quit()

Output

send an email with html content using a python program

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

'''Sending an email with an attachment using python'''
import smtplib
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart


msg = MIMEMultipart()
msg["subject"] = "Email with an attachment"
msg["From"] = "your_mail@gmail.com"
msg["To"] = "recipient@gmail.com"

# Text Emails
text = "Welcome to PySeek"

# HTML Mimetext object
body = MIMEText(text, "plain")
msg.attach(body)

file = "sample_file.pdf"
# Open The file in binary mode
file_content = open(file, "rb")
# Adds content type and a MIME header
part= MIMEBase('application', 'octate-stream')
part.set_payload(file_content.read())

# Encode the attachment
encoders.encode_base64(part)

# Adding header with the attachment filename
part.add_header('Content-Decomposition',\
f"attachment;filename={file}")

msg.attach(part)

smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('your_mail@gmail.com', 'Your_Password')

smtpObj.sendmail(msg["From"], msg["To"], msg.as_string())

smtpObj.quit()

Output

send email with attachment using python -PySeek

👉Visit AlsoCheck 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

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post