How to send emails using Python?
We can easily send emails using Python by using the following steps:-
1. Setting up the SMTP server using smtp.ehlo() and smtp.starttls().
2. Logging in to your account using smtp.login().
3. Creating a message by adding subject and body.
4. Sending the email using smtp.sendmail(sender, receipient, message).
In this tutorial, we will learn to use python to send emails using gmail. 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 services like yahoo mail, rediffmail, etc. to send emails using Python via SMTP.(You will have to use slightly different setting in that case.)
Installing smtplib for Python
You can easily install smtplib in Python by using ‘pip install smtplib’ in terminal(MacOS/Linux) or PowerShell(Windows):-
pip install smtplib
Setting up your gmail account
In order to send email using Python, you will have to set up your gmail account first. Open your gmail account. If you are not using 2-Step Verification, you will have to allow less secure apps from this link.
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.
Saving your login credentials as environment variables in Python
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 a simple email using Python via SMTP
We will be using the following code to send a simple email using Python via SMTP:-
# 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.
Sending email using Python to local debugging server
While we are testing/learning, it could be frustrating to use real email, so we will start a local debugging server in Python 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 instead of actual mailbox.
$ 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.
Using smtplib.SMTP_SSL() for sending emails in Python
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)
Sending email with attachment in Python
Sending email in Python with image as an attachment
We can also send emails with jpg, png, etc., image attachments by using message.add_attachment() to attach the image. We will use 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)
...
...
Sending email in Python with multiple images as attachments
To send multiple jpg, png, etc., images as attachment to an email in Python, we will add the name of the image files in a list and then loop through the list to attach them using message.add_attachment().
# 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:-
Sending email in Python with PDF or CSV as an attachment
For sending a pdf or CSV attachment in an email using python, we will use maintype=’application’ and subtype=’octet-stream’ while attaching the PDF or CSV using message.add_attachment().:-
# 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:-
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 message[“To”] equal to that list.
# python_send_email.py
contacts = ['example@gmail.com', 'example_2@gmail.com']
message['To'] = contacts
Sending HTML email using python
To send a HTML email 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) in message.add_alternative().
# 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.