Udit Vashisht
Author: Udit Vashisht


Use Python to send emails

  • 6 minutes read
  • 393 Views
Use Python to send emails

    Table of Contents

How to send emails using Python?

We can easily send emails using Python by using the following steps:-
1. Setting up the SMTP server using smtp.ehlo() and smtp.starttls().
2. Logging in to your account using smtp.login().
3. Creating a message by adding subject and body.
4. Sending the email using smtp.sendmail(sender, receipient, message).

In this tutorial, we will learn to use python to send emails using gmail. We will start with sending plain email using python and then learn to send advanced automated emails, HTML emails, emails with attachments etc. In this tutorial, we will be using gmail to send email via python, which is the most common email service used. However, you can use any other email services like yahoo mail, rediffmail, etc. to send emails using Python via SMTP.(You will have to use slightly different setting in that case.)

Installing smtplib for Python

You can easily install smtplib in Python by using ‘pip install smtplib’ in terminal(MacOS/Linux) or PowerShell(Windows):-

pip install smtplib

Setting up your gmail account

In order to send email using Python, you will have to set up your gmail account first. Open your gmail account. If you are not using 2-Step Verification, you will have to allow less secure apps from this link.

python send emails ...png

However, if you are using 2-Step Verification (which I highly recommend), you need to create app password for your account for this project from here. You can learn to create app passwords from google’s official documentation.

Saving your login credentials as environment variables in Python

We do not want to hard code our username and password, so we will be using environment variable to set them. Open the .bash_profile of your MacOS and save the email and password (or app password in case of 2-step verification) as under:-

$ nano .bash_profile
# .bash_profile
export EMAIL_USER="your_email"
export PASSWORD="your_password"
$ source .bash_profile

Sending a simple email using Python via SMTP

We will be using the following code to send a simple email using Python via SMTP:-

# python_send_email.py

import os
import smtplib

EMAIL = os.environ.get('EMAIL_USER')
PASSWORD = os.environ.get('PASSWORD')

with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    smtp.login(EMAIL, PASSWORD)
    subject = 'Python Send Email'
    body = 'This email is sent using python'
    message = f'Subject:{subject}\n\n{body}'
    smtp.sendmail(EMAIL, EMAIL, message)

Let me quickly go through each step.

  1. We have used os to use environment variables where we have saved our username and password.
  2. Then we have used the context manager, so that the connection ends by itself after the script is complete.
  3. Then we identified ourselves using smtp.ehlo(), then we put it in the connection mode using smtp.starttls() and logged in using smtp.login().
  4. Finally, we will draft the email by adding subject, body, message and send it using smtp.sendmail(sender, receipient, message). Running the script will send the simple email to the user.

python send emails _.png

Sending email using Python to local debugging server

While we are testing/learning, it could be frustrating to use real email, so we will start a local debugging server in Python using the following command. When we will run this, all the future emails which we will send using our script will be displayed on the terminal instead of actual mailbox.

$ python -m smtpd -c DebuggingServer -n localhost:1025

Now, we will have to make following changes to python_send_email.py :-

# python_send_email.py

# with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
with smtplib.SMTP('localhost', 1025) as smtp:    #add this and comment out the rest
    # smtp.ehlo()
    # smtp.starttls()
    # smtp.ehlo()
    # smtp.login(EMAIL, PASSWORD)

Now if we will run our python_send_email.py, it will be displayed in the terminal.

python send email !.png

Using smtplib.SMTP_SSL() for sending emails in Python

Instead of calling the server using smtp.ehlo() we will be creating a SSL connection from the very beginning using smptlib.SMTP_SSL() and instead of port 587, we will use port 465. Now, we will be taking advantage of EmailMessage class of email.message to create a message and finally smtp.send_message() to send that message. The modified code is as under:-

# python_send_email.py

import os
import smtplib
from email.message import EmailMessage #new

EMAIL = os.environ.get('EMAIL_USER')
PASSWORD = os.environ.get('PASSWORD')

message = EmailMessage()
message['Subject'] = 'Python Send Email'
message['From'] = EMAIL
message['To'] = EMAIL
message.set_content('This email is sent using python.')

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login(EMAIL, PASSWORD)
    smtp.send_message(message)

Sending email with attachment in Python

Sending email in Python with image as an attachment

We can also send emails with jpg, png, etc., image attachments by using message.add_attachment() to attach the image. We will use imghdr to find out the type of the image. Now place the image python_send_email.jpg in the same directory as the script python_send_email.py and change the code as under:

# python_send_email.py

import imghdr # new

...
...
with open('python_send_email.jpg', 'rb') as f:
    file_data = f.read()
    file_type = imghdr.what(f.name)
    file_name = f.name

message.add_attachment(file_data, maintype='image', subtype=file_type, filename=file_name)

...
...

python_send_email.png

Sending email in Python with multiple images as attachments

To send multiple jpg, png, etc., images as attachment to an email in Python, we will add the name of the image files in a list and then loop through the list to attach them using message.add_attachment().

# python_send_email.py
...
...

files = ['python_send_email.jpg', 'python_send_email_2.jpg']

for file in files:

    with open(file, 'rb') as f:  # new
        file_data = f.read()
        file_type = imghdr.what(f.name)
        file_name = f.name

    message.add_attachment(file_data, maintype='image', subtype=file_type, filename=file_name)

...
...

Look at the screenshot below, the new email has two attachments now:-

python_send_email_attachment.png

Sending email in Python with PDF or CSV as an attachment

For sending a pdf or CSV attachment in an email using python, we will use maintype=’application’ and subtype=’octet-stream’ while attaching the PDF or CSV using message.add_attachment().:-

# python_send_email.py
...

files = ['python_send_email.pdf', ]

for file in files:

    with open(file, 'rb') as f:  
        file_data = f.read()
        # file_type = imghdr.what(f.name) 
        file_name = f.name

    message.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name) #new

...

The screenshot below shows all the three emails sent:-

python_send_email_..png

Send email to multiple recepients using python

To use python to send email to multiple persons, we can add their email addresses in a list and then set message[“To”] equal to that list.

# python_send_email.py

contacts = ['example@gmail.com', 'example_2@gmail.com']
message['To'] = contacts

Sending HTML email using python

To send a HTML email using Python, which is very prevalent in newsletters etc., you will have to define html content and plain text (for those users who have switched off HTML) in message.add_alternative().

# python_send_email.py

message.add_alternative("""\
<!DOCTYPE html>
<html>
    <body>
        <h1>This is an HTML Email!</h1>
    </body>
</html>
""", subtype = 'html')

If you have any query, feel free to leave a comment.



Related Posts

Python unittest module - How to test your python code?
By Udit Vashisht

Python unittest module

Why to unit test your python source code?

All programmers want their code to be impeccable, but as the saying goes, to err is human, we make mistakes and leave bugs in our source code. Here is where the unit testing comes to our rescue. If you ...

Read More
Matplotlib Tutorial in Python | Chapter 2 | Extracting Data from CSVs and plotting Bar Charts.
By Udit Vashisht

Matplotlib Tutorial in Python

Chapter 2 | Extracting Data from CSVs and plotting Bar Charts

In the last chapter, we learned to draw simple plots in Matplotlib and further customizing it.In this chapter we will be learning to extract data from external sources like CSV and creating ...

Read More
How to host and schedule your python script on PythonAnywhere?
By Udit Vashisht

In our last post here, we learned how to create a python script which will automatically delete your messages from gmail account based on a query.

The complete ready-to-use code can be found here.

Follow the steps in the above tutorial to download the ‘credentials.json’ file and ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list