How to send email in Python?

How to send email in Python?

How to send email in Python?


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 (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 ( Copy the below sample code and replace with your SMTP settings:

import smtplib 

smtpServer = "";

smtpPort = 25;

smtpUsername = "Your_User_Name";

smtpPassword = "Your_Secret_Password";

toAddress = "";

fromAddress = "";

body = """From: From Pepipost <>

To: MrRobot <>

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 !!


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: {'': (553, '5.7.1 <>: Sender address rejected: not logged in')}

smtplib.SMTPRecipientsRefused: {'': (553, '5.7.1 <>: 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. 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  to check whether your outgoing port is open or not. It is very handy to use with the simple curl command.

$ curl
Port 8080 test successful!
Your IP: 

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

telnet 25

3. 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 "", line 23, in 


  File "/usr/lib64/python2.7/", 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


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.