Send Email using Python3

Send Email using Python3

In this tutorial, we will be learning about how to send an email using Python3. This article is a part of a project Warehouse Surveillance System. Warehouse Surveillance System is a software solution that detects movement in a video stream and raises an alert with a snapshot of the same to the owner.

Getting Started

In this tutorial, we will be using Python's built-in library smtplib. The smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. You can learn more about smtplib from the official documentation.

Setup Gmail Account

In this tutorial, we will use a Gmail account to send emails. We can use two different ways to send email using Gmail.

  1. Gmail SMTP Server: Gmail provides an SMTP server to send email using your Gmail account for free. You need to enable permission for Less secure apps access to use your Gmail account with Python. You can enable this permission by visiting your Google Account. There should be an option to enable less secure apps access under the Security section.

    Note: This feature makes it easier for others to access your account, Don't use this feature in your personal account. Create a test Gmail account for this tutorial. Also, This feature will be disabled by Google from May 30, 2022

  2. Gmail API: Google provides Gmail API for developers. The Gmail API is a RESTful API that can be used to access Gmail mailboxes and send mail. For most web applications the Gmail API is the best choice for authorized access to a user's Gmail data.

In this tutorial, we will use the Gmail SMTP Server method to send emails. To send an email using an SMTP server. We will need the following details :

  • User Email ID: Email ID which will be used to send email
  • User Password: Password of the Email ID which will be used to send the email
  • Reciever's Email ID(s): Email ID of the receiver(s), to whom you want to send the email

Implementation

  • Create a file named config.json. We will use this file to save the google credentials and other configuration values.
    {
        "sender_email": "test.email.ioscript@gmail.com",
        "password": "XXXXXXXXXXXXX",
        "host": "smtp.gmail.com",
        "port": 465
    }
  • Create a file named main.py.

import smtplib
import json
import ssl


class emailService:
    __sender_email = ""
    __sender_pass = ""
    __smtp_host = ""
    __smtp_port = 25

    def __init__(self):
        config = self.read_email_config()
        self.__sender_email = config['sender_email']
        self.__sender_pass = config['password']
        self.__smtp_host = config['host']
        self.__smtp_port = config['port']

    def read_email_config(self):
        file = open("config.json")
        config = json.load(file)
        return config

    def connection_init(self):
        ctx = ssl.create_default_context()
        server = smtplib.SMTP_SSL(
            self.__smtp_host, self.__smtp_port, context=ctx)
        server.login(self.__sender_email, self.__sender_pass)
        return server

    def senderemail(self):
        return self.__sender_email


def main():

    email_service = emailService()
    email_client = email_service.connection_init()

    receiver_email = "test.email.ioscript@gmail.com"
    msg = "Hello World!"

    email_client.sendmail(email_service.senderemail(),
                          receiver_email,
                          msg)


if __name__ == '__main__':
    main()

Note: config.json and main.py should be in the same directory

Let's see what's happening in the above code. We have a config.json file that contains the email id and password which will be used to send the email. It also contains the host and port for google's SMTP server. We have another file main.py, which contains the python code to send the emails.

In main.py we have imported smtplib, json, and 'ssl' libraries. You can download these libraries using python package manager pip or conda. smtplib is used to create or connect to an SMTP server and send the email. json library is used to read the configurations from the config.json file. ssl library is used to create a secure connection with the SMTP server.

We have created a class emailService, Which implements a constructor and three methods. The constructor reads calls the method read_email_config, which reads the config file, and updates the google account credentials to private properties. connection_init makes the connection to the SMTP server and returns a client to be used to send emails.

In the main function, we have created an object of the emailService class. We use the connection_init() method to initialize the connection to the SMTP server. We use the send_email() method to send an email to the user. You can find more about the send_email() method in the official documentation.

Before You Leave

If you found this article valuable, you can support us by dropping a like and sharing this article with your friends. You can find more articles in this series here

You can sign up for our newsletter to get notified whenever we post awesome content on Golang.

You can also let us know what you would like to read next? Drop a comment or email @

Reference

Python Docs

Frame 1.png

Did you find this article valuable?

Support ioScript.org by becoming a sponsor. Any amount is appreciated!