Udit Vashisht
Author: Udit Vashisht


Use Python to send email using SMTP

  • Aug. 21, 2019, 4:23 p.m.
  • 6 minutes read
  • 285 Views
Use Python to send email using SMTP

Use Python to send emails

In this tutorial, we will learn to use python to send emails. If you are new to python, you can see our beginner’s series. In case you are having trouble installing Python, you can see our posts on installing python on MacOS and Windows.

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 service.(You will have to use slightly different setting in that case.)

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.

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 simple email using python

Now create a file called ‘python_send_email.py’ and import smtplib and write down the following code:-

# 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.

We have used os to use environment variables where we have saved our username and password.
Then we have used the context manager, so that the connection ends by itself after the script is complete.

Then we identified ourselves using smtp.ehlo(), then we put it in the connection mode using smtp.starttls() and logged in using smtp.login().

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 local debugging server

While we are testing/learning, it could be frustrating to use real email, so we will start local debugging server 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.

$ 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

Cleaning it up

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)

Python - send email with attachment

Now we will be sending the emails with attachment. In order to send an image we will be using 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 mail with multiple attachments using python

To send multiple images, we need to add the name of the images in a list and then loop through the list to attach them to the message.

# 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 a pdf attachment

For sending a pdf attachment in an email using python, we will not need imghdr and will make following changes in our code:-

# 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 that list to “To”

# python_send_email.py

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

Sending HTML email using python

To send an email having HTML 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)

# 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.

This post is inspired from a video tutorial by Corey Schafer.



Related Posts

Pie Charts in Python | Matplotlib Tutorial in Python | Chapter 3
By Udit Vashisht | 2 months, 2 weeks ago

Matplotlib Tutorial in Python

Chapter 3 | Creating Pie Charts in Python

In this chapter, we will learn to create Pie Charts in Matplotlib in Python. Pie Charts are an intiutive way of showing data, wherein each category is shown as a portion of the pie. Let ...

Read More
How to host and schedule your python script on PythonAnywhere?
By Udit Vashisht | 9 months, 3 weeks ago

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
Filling Area on Line Plots | Matplotlib Tutorial in Python | Chapter 5
By Udit Vashisht | 2 months, 2 weeks ago

Matplotlib Tutorial in Python

Filling Area on Line Plots | Chapter 5

Matplotlib Line plots are a good way to represent your data. But sometimes you need more than that to make your data self-explaining. In such a case, filling the area between or under a Maplotlib Line Plot ...

Read More
Search