SaralGyaan, Saral Gyaan, Saral Gyan is website which provides free tutorials of Python for absolute beginners in English and Hindi, Learn Python in Hindi, Learn Python for absolute beginners, Learn Python, bootstrap, django, git

Hari S
Author: Hari S


Use Python to send Email

  • Aug. 21, 2019, 4:23 p.m.
  • 6 minutes read
  • 209 Views
Use Python to send Email

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, use python to send email 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 user name 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’ in the same folder as and import smtplib and write down the following code:-

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

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 on its own after the script has completed.

Then we identified ourselves using smtp.ehlo(), then we put it in the connection mode using smtp.starttls() and finally 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 server

While we are testing/learning, it could be frustrating to use real email, so we will start local server using the following command. When we will run this, all the future email 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 :-

# 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

Firstly, 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 be using 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 the message. The modified code will be as under:-

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 with Attachement

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.

...
...

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 a email using python, we will not need imghdr and will be making following changes in our code

...

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”

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)

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

Plot Time Series in Python | Matplotlib Tutorial | Chapter 8
By Hari S | 2 weeks, 1 day ago

Plot Time Series in Python using Matplotlib

Plot Time Series in Python | Chapter 8

In this tutorial we will learn to plot time series data in Python using Matplotlib. We will also be using pandas dataframe to plot time series data in python from ...

Read More
Pie Charts in Python | Matplotlib Tutorial in Python | Chapter 3
By Hari S | 3 weeks, 4 days 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
Chapter 7- Numbers, Conversions and Operators
By Hari S | 6 months, 2 weeks ago

In the previous chapter, we learned about various data types. From this chapter onward, we will learn in detail about each data type.

Numbers

This data type stores the numeric values and is immutable. For the beginners, it is sufficient to understand that immutable objects are those which can not ...

Read More
Search