How To Send Simple Email Using Python

Share Your Love

In this post, I am explaining to you How To Send Simple Email Using Python?

This post will show you how to use Python to send an email and how to integrate it into your existing data science projects.

Table Of Contents

Introduction

We always want to make sure that any data science project we design and deploy is going smoothly and that we are notified if there are any difficulties. It may be far easier to keep track of one main project on a daily basis than it is if you are in charge of four projects, for example. Rather than inspecting the code and output every time, we’d prefer to be told when the code was successfully executed or if there were any problems. This is why we’re going to talk about how to make email notifiers in Python. What we want is for an automated email to be sent to our email address based on a trigger of your choosing. Let’s see how we can use Python to automate this procedure and send emails.

You will learn how to send automated emails using Python in this lesson. We’ll use a Gmail address to communicate (but you can extend the same code to work with any other email service provider).

Sending Email in Python

There are four main steps in sending an email using Python:

  1. Connect to an SMTP server
  2. Log in to the server
  3. Create a message
  4. Send the email

To continue in this article, please import the smtplib library:

import smtplib

Part 1: Connect to an SMTP server

The SMTP (Simple Mail Transfer Mechanism) is an email transmission communication protocol. Every email service provider has an SMTP address, which you may find in your mail client’s settings. We’ll also require an SMTP port (in our case we will use port 587).

Here are a few examples: SMTP for Gmail is smtp.gmail.com, and SMTP for Outlook is smtp-mail.outlook.com. Both of these are capable of sending emails on port 587.

Let’s construct a server variable that will hold an instance of smtplib with our email SMTP information:

server = smtplib.SMTP(host='smtp.gmail.com', port=587)

After that, we must “identify” our server and allow it to begin “talking” to the SMTP:

server.ehlo()

Finally, for communication between the email server and the client, we must establish a TLS (Transport Layer Security) connection:

server.starttls()

All of the above procedures work together to create a secure connection between us and the email server. Consider it as if you had just visited www.mail.google.com.

Part 2: Log in to the server

Now it’s time to sign in to our account.

This section is pretty simple, and all you have to do to log in is run one line of code with your email login and password credentials:

server.login('your email address', 'your password')

Going to the Gmail sign-in page, inputting your credentials, and clicking “Login” is essentially the same thing. We’ve entered our email account at this stage.

Part 3: Create a Message

We wish to compose a new email after logging into our email account. There will be two pieces to the email: a topic and the actual content. Let’s make both of these things:

subject = 'This is my subject'
body = 'This is the message in the email

To use smtplib to process this message, we’ll need to create a single object that contains both the topic and the body. This may appear strange, but it is the formatting that must be completed in order for the client to process the message:

message = f'Subject: {subject}\n\n{body}'

The email client detects the formatted string and uses the first portion as the email topic and the second part as the email text.

Part 4: Send the Email

We logged into our email account and sent a message at this point. Now, all we have to do is send it and log out of the email account. We’ll need three things to send it: the sender’s email, the recipient’s email, and the message:

server.sendmail('your email address', 'recipient email address', message) server.quit()

Perfect! You’ve just sent your first email using Python!

Sending Email using Functions

In general, we like to have automated email senders as reusable functions rather than generating a raw Python script when working with them.

First, let’s try to combine all of the preceding phases into a single function:

def send_email(subject, body):
    server = smtplib.SMTP(host='smtp.gmail.com', port=587)
    server.ehlo()
    server.starttls()
    server.login('your email address', 'your password')
    message = f'Subject: {subject}\n\n{body}'
    server.sendmail('your email address', 'recipient email address', message)
    server.quit()

It’s reusable in any portion of your existing project script once we’ve built it up in the functional form. However, there is a catch: if the email does not go through, it will damage the entire script of the project you are working on. So let’s add some safety nets to avoid your main project script from crashing.

We’ll use the Python try/except statement to aid us in this endeavour. It will make an effort (try) to send the email, but if it fails, it will continue to run the rest of your project script:

def send_email(subject, body):
    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login('your email address', 'your password')
        message = f'Subject: {subject}\n\n{body}'
        server.sendmail('your email address', 'recipient email', message)
        server.quit()
    except:
        pass

You can put it anywhere in your project script in this functional form and let it run. It’s important to remember that this function now requires two arguments: topic and body. As a result, when you add it and want it to run, it should look like this:

send_email('this is the subject', 'this is the body')

The above function should send an email with the subject “this is the subject” and the email’s content “this is the body.”

Final Note!

The purpose of this essay was to look at how to send emails in Python. Understanding the method and having the skills to integrate it into an existing data science project should be a solid starting point.

If you have any queries or recommendations for changes, please leave them in the comments section below.

Share Your Love
Default image
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Co-founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 343

Newsletter Updates

Enter your email address below to subscribe to our newsletter