Published on 2019-08-07· Updated on 2020-05-20
The author voluntarily contributed this tutorial as a part of Pepipost Write to Contribute program.
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.
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 = "[email protected]"; fromAddress = "[email protected]"; body = """From: From Pepipost <[email protected]> To: MrRobot <[email protected]> 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.
smtplib.SMTPRecipientsRefused: {'[email protected]': (553, '5.7.1 <[email protected]>: Sender address rejected: not logged in')} smtplib.SMTPRecipientsRefused: {'[email protected]': (553, '5.7.1 <[email protected]>: Sender address rejected: not owned by user MyUserName')}
In case, you are getting some errors related to SMTPRecipientsRefused, then;
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
3. There might be possibilities that MTA (Mail transfer agent e.g POSTFIX) is down if you are using localhost as an SMTP server.
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.
The script is showing that mail has been successfully sent, but it's not yet received in your GMAIL inbox.
Few learnings:
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.
Netcorecloud's toolkit is the solution to all your email problems.
Netcore connects & unifies your data across all sources, connects to your marketing channels and provides you with control over AI Powered automation and personalization.
Ashish Tiwari
Open source guy | Linux lover | Dev evangelist @ Pepipost