Published on

How to Send emails with Python


Table of contents

Emails have been important part of communicating online for a long time now. While working with Python (or any other language), you may want to send emails to your customers using your web app, or via a script to send some notification about the product, inform subscribers about their subscription and many more things etc.

In this blog post, we will be sending emails via SMTP protocol using Python. This is a quickstart guide, a basic knowledge of Python statements is a pre-requisite. By the end of this tutorial, you will have a fair understanding of what are different ways to send emails with Python along with the boilerplate code.

Why use Python to send an Email?

Python 🐍, being one of the most easiest and popular programming language, can be used for sending emails. It makes sending emails much easier both the plain emails and fancy-html emails with attachments etc. Using builtin python's builtin email module and just a few lines of codes, you can send out emails in no time.

Different email libraries available for python :

  • smtplib
  • email

SMTP protocol and emails

There are mainly three protocols which are used to send and receive an email over the internet. Those are :

  • Post Office Protocol (POP)
  • Internet Message Access Protocol (IMAP)
  • Simple Mail Transfer Protocol (SMTP)

POP3 and IMAP protocols are used for receiving emails and SMTP protocol is used for sending emails. Like a typical API response-request cycle, in emails also you need a Server to send an email and a Client to receive an email.

Setting up the environment for sending Emails

  1. Python : Duh! before we move ahead, make sure you have Python installed on your computer. If not installed already, follow this article to install python on your system.
  2. PIP : Most likely you will have it installed with Python itself, make sure it's updated to latest version by running the following command :
    pip install -U pip
  3. An SMTP Server : For sending an email, we need a SMTP Server, you can either choose to create one using Python or you can also opt for third-party services that provide you with SMTP as a service. Some of these services are Amazon SES, Mailgun, Postmark, Sendinblue and SendGrid etc.

Sending emails with Python

To send an email we will use the python inbuilt module smtplib which make use of RFC 821 Protocol. smtplib is just used for creating a smtp client session. Each object created using smtplib is a client session using which we could send our fancy email. However, to send an email we will need an SMTP server. We will use google's SMTP server in this tutorial to demonstrate sending of an email.

Some things to remember :

  • Gmail doesn't directly give permission to login using your email and password. You first need to turn 2-step verification On.
  • After this you have to create an app and 16-character code will get generated. You will use this code as a password instead of your real password to login with smtplib to your email.
  • You can create your app password by following this

Follow these steps to send email using python.

  1. import the smtplib module first. It comes built-in with python so you don't have to install it using pip.
import smtplib

2. Now, keep your credentials in python variables. You can also keep your credentials in a separate python file and then install it here.
   sender_email = "<your_email>"
   sender_password =  "<your_email's_password>"
   smtp_server = ""
   smtp_port = 465
   receiver_emails = ["<recipient_email>"]
  1. Then create a smtp client and login using your email credentials.
    client = smtplib.SMTP_SSL(smtp_server,smtp_port)
  2. After this you just have to send an email to the recipients.

Sending email with attachments using Python's email library

For now we just send a simple text inside mail.Now, let's make it more interesting 😀 by sending some html and attachments.

  1. To send email with attachments we have an email python module which lets us design our email in some fancy manner.

  2. Let's send a pdf in the attachments of the email. Following code will add a pdf as an attachment.

    from email.mime.multipart import MIMEMultipart
    from email.mime.application import MIMEApplication
    msg = MIMEMultipart()
    msg['subject'] = "Sending emails is Fun!"
    with open("AwesomeFile.pdf", 'rb') as fp:
        pdf_data =
    pdf_attach = MIMEApplication(pdf_data, _subtype="pdf")
    client = smtplib.SMTP_SSL(smtp_server, smtp_port)
    client.login(sender_email, sender_password)

    In the above example, we are reading the PDF as binary and attaching it to email with MIMEApplication class. This class is responsible for encoding attachments to transmit via SMTP server.

  3. And that's it, that's how you send email with attachment in Python.

Sending HTML emails using Python's email library

Often times you will want to send a HTML template via email. Which is how most of the email campaigns, user notifications, alerts go out now a days. We'll now demonstrate how HTML emails can be sent out with Python's email library.

from email.mime.text import MIMEText

html_code = """
        <h3 style="background-color: blue;">This is Testing Html</h3>
msg.attach(MIMEText(html_code, 'html'))

client = smtplib.SMTP_SSL(smtp_server, smtp_port)
client.login(sender_email, sender_password)
client.sendmail(sender_email, receiver_emails, msg.as_string())

Sending Email using Python's Yagmail library

If you are using gmail then the yagmail module is just made for you only. yagmail (Yet another Gmail) is also an SMTP client module made to simplify the sending of an email with ease. With just a few lines of code you can send your email using yagmail. Let's code the solution :

import yagmail

sender_email = "<your_email>"
sender_password =  "<your_email's_password>"

client = yagmail.SMTP(sender_email, sender_password)
    "Testing mail",
    "<h2>this is testing mail</h2>",

yagmail abstracts out a lot of syntax for you. It makes sending attachments, HTML easy.

Sending email using third party providers

There are multiple email as a service provider available in the market. Most of which provide both SMTP Server or a direct REST endpoint to send out emails using Python. Some of the popular and recommended providers according to us are :

  1. Amazon Simple Email Service (SES)
  2. SendGrid
  3. Mailgun
  4. Postmark
  5. Mailchimp

If you are using a third party SMTP servers, then the above discussed methods can be used to send emails. Let's take an example of when you want to use REST API to send emails.

Sending email using Mailgun's Email API

import requests

def send_simple_message():
        auth=("api", "YOUR_API_KEY"),
        data={"from": "Excited User <mailgun@YOUR_DOMAIN_NAME>",
            "to": ["", "YOU@YOUR_DOMAIN_NAME"],
            "subject": "Hello",
            "text": "Testing emails via Mailgun!"})


Ending Notes

And that's it, now you know all the various ways you can send out emails using Python. Do comment, and let us know of any feedback or suggestions. Happy Learning!