How to send email in Python?

 In All Tutorials
Last Updated On August 08, 2019

Python is the most preferable language and widely used by developers. Sending an email with Python is comparatively easier over SMTP protocol. There are lots of libraries available on the internet, but the most preferable library is ‘smtplib’.  In this guide, you will learn how to send an email in Python and what are the common problems & their solutions which arise while email sending through smtplib.

Prerequisites before you Start Emailing

  1. You need python 2.7 or above and respective pip (package installer).
  2. You must be having an SMTP server installed on your localhost or login credentials of some third party SMTP platform (e.g Pepipost, Sendgrid, etc.) OR just start with your Gmail SMTP settings.

Sending a Test Email using Python

Step 1: Install the smtplib client.

Nowadays this library comes by default in the latest OS like centOS 7.

To check, if smtplib already installed you can use below command :

python -c "import smtplib"

If the library is not present, you will get the below error response:

Traceback (most recent call last):

  File "", line 1, in 

ImportError: No module named smtplib

Not to worry if the library is not there. You can install it by just firing below command: 

pip install smtplib

You might get below error if you are using pip package version 8.1.2 or below. 

Could not find a version that satisfies the requirement smtplib (from versions: )

No matching distribution found for smtplib

You are using pip version 8.1.2, however version 19.2.1 is available.

You should consider upgrading via the 'pip install --upgrade pip' command.

Just upgrade the pip package in case you get the above dependency error:

$ sudo pip install --upgrade pip

On a successful upgrade, you will be getting a success output something like this;

Cache entry deserialization failed, entry ignored Collecting pip Downloading https://files.pythonhosted.org/packages/62/ca/94d32a6516ed197a491d17d46595ce58a83cbb2fca280414e57cd86b84dc/pip-19.2.1-py2.py3-none-any.whl (1.4MB) 100% |████████████████████████████████| 1.4MB 650kB/s Installing collected packages: pip Found existing installation: pip 8.1.2 Uninstalling pip-8.1.2: Successfully uninstalled pip-8.1.2 Successfully installed pip-19.2.1

Now, just try again with "pip install smtplib", and you should be able to install smtplib successfully. If not, please share your error below in comments.

 

Step 2: Create a test python file (mail.py). Copy the below sample code and replace with your SMTP settings:

import smtplib 

smtpServer = "smtp.pepipost.com";

smtpPort = 25;

smtpUsername = "Your_User_Name";

smtpPassword = "Your_Secret_Password";

toAddress = "testuser@mydomain.com";

fromAddress = "from@pepipost.com";

body = """From: From Pepipost <from@pepipost.com>

To: MrRobot <test_recipient@gmail.com>

MIME-Version: 1.0

Content-type: text/html

Subject: SMTP test email

This is an e-mail message to be sent in HTML format using smtplib.

This is HTML message.
This is headline.

""" mailServer = smtplib.SMTP(smtpServer , smtpPort) mailServer.starttls() mailServer.login(smtpUsername , smtpPassword) mailServer.sendmail(fromAddress, toAddress , body) print(" \n Sent!") mailServer.quit()

Step 3 : Ready to shoot !!

python mail.py

Once the email is successfully sent, the code should return a success message as ‘Sent!’. Check your inbox 🙂

There couple of other advanced parameters too e.g. attachments, send as plain text etc available in smtplib. You can refer to the official documentation for  more details.

Few Common Problems which you might encounter while sending emails with Python

Exception 1

smtplib.SMTPRecipientsRefused: {'xxxxxxx@gmail.com': (553, '5.7.1 <from@mydomain.com>: Sender address rejected: not logged in')}

smtplib.SMTPRecipientsRefused: {'xxxxxx@gmail.com': (553, '5.7.1 <from@mydomain.co>: Sender address rejected: not owned by user MyUserName')}

In case, you are getting some errors related to SMTPRecipientsRefused, then;

  1. Trying to send an email without login or authentication (i.e. mailServer.login()). 
  2. Try whitelisting your sender domain. Your sender domain (i.e. mydomain.com) might not be allowed/whitelisted on the host SMTP server. In case you are using a third-party SMTP, then make sure the service provider has already whitelisted your sender domain.

Exception 2

socket.error: [Errno 111] Connection refused

In case you're getting the socket error, then this is mostly to do with your SMTP port:

  1. Make sure you have specified the correct outgoing SMTP port. It is possible connection getting close by SMTP server while trying to reach an incorrect port.
  2. There might be a case, where the host server has actually blocked your outgoing SMTP port. In such a case, you can contact your hosting provider and get it unblocked. You can use portquiz.net  to check whether your outgoing port is open or not. It is very handy to use with the simple curl command.

    $ curl portquiz.net:8080 
    
    Port 8080 test successful!
    
    Your IP: 103.198.98.29

    Or you use also use simple telnet command to check the port status too:

    telnet smtp.pepipost.com 25
  1. There might be possibilities that MTA (Mail transfer agent e.g POSTFIX) is down if you are using localhost as an SMTP server.

Exception 3:

Traceback (most recent call last):

  File "mail.py", line 23, in 

    mailServer.starttls()

  File "/usr/lib64/python2.7/smtplib.py", line 643, in starttls

    raise SMTPException("STARTTLS extension not supported by server.")

smtplib.SMTPException: STARTTLS extension not supported by server.

This mainly occurs when your SMTP server does not provide a secure connection. In such a case, you can consult with your SMTP service provider or you can simply remove mailServer.starttls() from your code.

Exception 4:

The script is showing that mail has been successfully sent, but it's not yet received in your GMAIL inbox.

Few learnings:

  1. Gmail does reverse DNS lookup on IP address from which email has been received. If there is no domain found, it will simply refuse the email packet.  This is usually to avoid spammers.
  2. Just check whether you have enabled less secure app.

Note: You can more debug your code by just enable debug mode

mailServer.set_debuglevel(1)

In this article, I tried to cover some of the basic concepts of how you can send an email using Python. Sending Emails using Python is easy but a small mistake might just lead to a blunder. Therefore I have also mentioned some of the common problems, exceptions, and queries which arises when you send an email using Python.

I hope you liked the article. Feel free to leave your valuable comments below.

Recent Posts

Leave a Comment

We are always looking for fresh talent to contribute to our blog. If you have a knack for writing and a passion for email marketing, we would love to have your post on our Guest Blog .

Submit a Guest Post
Pepi thinking

Start typing and press Enter to search

Thank you for your details!

Fill out your information below, and we will send you a PepiAlert, that will describe your domain’s email deliverability situation. Please note that your email address must match the domain, or the domain must be owned by the company matching the email address. We have the right to refuse the request, if we can’t verify the information.

*All fields are required



github-community