Send Mails in Python

Sending Emails with Python

Hello everyone and welcome to this tutorial on how to send emails using Python. Before we begin, you can download a free copy of my Python Pocket Manual explaining and demonstrating the use of Python programming language. It also contains exercises to help you assimilate how to efficiently use Python.

CLIENT AND SERVER TECHNOLOGY – A BRIEF INTRODUCTION

Back to sending emails with Python. Before we start coding, let’s understand the underlying technology behind Client and Server as it serves as the basis for sending and receiving mails.

When browsing web pages, the Client (usually the browser or your machine) sends a request to the Server (the server is basically another computer system that hosts these web pages). The server receives the request, fetches the website/web page(s) and sends the request back to the client via a protocol – HTTP (Hypertext Transfer Protocol). The client on receiving the request renders the web page on the screen via your browser. The same principle applies to sending and receiving an email message.

The mail server uses a protocol for these procedures. This protocol is the SMTP. The SMTP stands for Simple Mail Transfer Protocol. It is meant to aid in the sending and receiving of emails as efficiently and as easy as possible. There are different SMTP servers eg. smtp.gmail.com, smtp.mail.yahoo.com etc. and they use different authentication methods and port numbers. For a list of different SMTP Mail Servers, their port numbers, and Authentication type, please check the arclab article.

SMTPLIB Python Module

Python provides developers with the smtplib module to enable them to write mail applications. The SMTP has several commands which are available in the smtplib module. It exposes these methods to help communicate, deliver, and receive emails from the mail servers. We are going to write an application to send a message to one of the mail servers ….Gmail using the module in python. The process involved must be followed sequentially:

  1. Creating a Connection Object – This involves making a connection to the email servers through the connection object
  2. Confirming the Connection
  3. Setting up the SMTP
  4. Logging in to our email account
  5. Sending the Message
  6. Quitting the Connection object to free resources.

We will be using Juypyter Notebook in Visual Studio Code and run each cell starting (from process 2) as mentioned above. Likewise, other notable environment of choice is –

1) Python IDLE (installs with python by default)

2) Jupyter Notebook (The official Jupyter Notebook application) – Available Here

3) Cocalc (An Online Jupyter Notebook) – Free Signup here

Let’s start with the procedure.

This application requires steady internet connection. Please, make sure that your antivirus or your firewall settings in your computer is allowed to check the internet if for any reason the code didn’t work as intended. Follow the guidelines for allowing third party apps from your mail provider to ensure smooth running of the application.

1) Start Visual Studio Code (Please follow the guide in the Python Pocket Manual to learn how to download and install Visual Studio Code) and activate the Jupyter package by Pressing Ctrl + SHIFT + P. This opens the Command Palette.

2) Type Jupyter and Select Create New Jupyter Notebook

Fig 1 – Search for Jupyter Notebook

A new Jupyter Notebook environment with the name Untitled-1.ipynb will be created. Save the notebook as email.ipynb making sure that the All Files(*.*) is selected as the Save as type.

Fig 2 – Jupyter Notebook Environment in Visual Studio Code

3) Type the following code as shown in Fig 3 and run the cell by clicking the Execute this Cell button (red arrow in Fig 2)

Fig 3 – Coding and Executing the Current Cell

Notice that if there is any missing module that is required to run the code, Visual Studio Code will download and install it before executing the code. The result of the execution is shown in the OUTPUT window.

To learn more on how to setup Jupyter Notebook in Visual Studio Code Environment, please visit the visual studio code website
Fig 4 – Result of the Current Executed Cell

The code S = smtplib.SMTP(‘smtp.gmail.com’) in Fig 3 establishes a connection by creating a connection object to Google’s Gmail SMTP Server. We have also imported the smtp python class by using the import smtplib. The getpass class library will be used to hide/mask our username and password when we are trying to login to our gmail account.

4) Type the code in Fig 5 and run the cell to see the result in Fig 6.

Fig 5 – Sending a request to the Server

The ehlo( ) method is used by our application to send a request to the SMTP Server to identify itself (by creating a network handshake) and to initiate a conversation. Upon receiving the request, the server will respond with a reply code of 250. This means that the requested mail action completed.

Fig 6 – Server Reply Code

To learn more about the different server response code, have a look at Mozilla’s HTTP response status codes for more information.

5) To make sure that our usernames and password are sent securely, we need to create a TLS (Transport Layer Security). This method responsible for handling this is the starttls( ). This makes sure that all the delicate username, password and email content are encrypted first before sending it to the server over the network.

Fig 7 – Encrypting our Mails

Type the code and run the cell. The server responded with a 220 reply code. This means that the server is ready to receive our message securely. The next thing to do is to write the code for creating the mail itself.

CREATING THE EMAIL COMPONENTS

6) Type the code below and run the cell:

Fig 8 – Masking Email with Getpass

Visual studio code will display a textbox where you can add your email address. The getpass( ) masks sensitive information

7) Enable less Secure Apps Access Option/App Password

We need to enable the less secure app access option from our email application settings before we can write the code for the password. The Enable less secure app access allows third party applications (your python app in our case) to send and/or receive messages to and from your email account. The App Password is an extended process where a password will be created by Google (this password is different from your email password) which you must supply in your python code. To learn more about the App Password, please visit the Google Sign in with App Password Help page.

To enable the less Secure App Access, do the following:

a) Sign in to your Gmail Account

b) Click the Google Account located on the top right corner of the page >> Click Manage your Google Account

c) Click on the Security command on the left side of the screen

d) Scroll down and locate the less Secure App Access Section and click the OFF option

e) Toggle the Allow Less Secure Apps OFF to ON and click back

Fig 9 – Enabling Less Secure App Access in Gmail

Heads up! In Fig 9, this option will be discontinued on May 30, 2022. The only other option to use is by creating an App Password for your application by using the link above. Make sure to enable the 2FA (Two Factor Authentication) first before generating the App Password.

8) Type the code for the password and input your normal Gmail password (or App Password generated by Google) after executing the cell (as we did in the case of email – Fig 8 above)

9) log in to your Gmail account, type the code shown below and execute the cell.

Fig 10 – login to your email

The server replied with a response code of 235. This means it has accepted the login

10) Type the remaining code shown in Fig 11 and execute the cell

Fig 11 – Sending the mail

The fromaddress and toaddress variables save the email address of the sender and the receiver respectively. Since we will be sending the mail to ourselves, you just type your mail in both.

The subject creates the subject of the email

The message represents the body of the mail.

The themessage variable collects all the mail objects outlined above and sends them to the server via the Sendmail(). Run the cell labelled 1 from fig 10 and the output will be similar to the one with the red arrow. This means our message was successfully sent. Now, check your mail and confirm that the content was sent successfully.

The full code is shown below:

import smtplib
import getpass

connObjt=smtplib.SMTP('smtp.gmail.com',587)
connObjt.ehlo()

connObjt.starttls()

email=getpass.getpass("Your Email Address goes here: ")
password=getpass.getpass("Your Password goes here: ")
connObjt.login(email, password)

fromaddress=email
toaddress=email
subject=input("Enter the mail Subject here: ")
message=input("Enter body of the message here: ")
the_message="Subject: "+subject+'\n'+message

connObjt.sendmail(fromaddress, toaddress, subject, the_message)

connObjt.quit()

Leave a Comment

Your email address will not be published. Required fields are marked *