No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python Send Email with SMTP over SSL

by Khaleel O.
September 15, 2021
in Python
Reading Time: 6 mins read
A A
python send email smtp
python send email smtp

Let’s use Python to Send an Email with SMTP over SSL. We will send a plain text email. You will need a GMAIL Account to complete this tutorial. Don’t have one? Go HERE to set one up. Let’s get started! ✨✨

Getting the GMAIL App Password

First we need to set up an App Password in our Gmail Account. First go to the upper right hand corner of the GMAIL Inbox where your Google account picture/avatar is located, click the image and then click Manage your Google Account. (Click HERE to skip to the Python Code Section if you have already setup an app password.)

Next, click Security on the left menu of the next page.

Find the Signing in to Google section and click App Passwords subsection.

NOTE: If you don’t have 2-Step Verification turned ON, you will be prompted to set it up before you can access the App Password section

On the App Passwords page, you will set your app password. Click the Select App dropdown and select Other (Custom Name) item.

python send email smtp

You will then be asked to give the App Password a name. When you give it a suitable name, then you click GENERATE:

When you click GENERATE a new window will open with your App Password copy this 16-character value and keep it safe. (the real value is not shown below).

python send email smtp

Now that we have our App Password we can finally write our Python Script to send a simple email message.


Python Code to Send Email

This our code:

import smtplib, ssl

sender_email = "[email protected]"
receiver_email = "[email protected]"
message = """\
Subject: It Worked!

Simple Text email from your Python Script."""

port = 465  
app_password = input("Enter Password: ")

context = ssl.create_default_context()

with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
    server.login("[email protected]", app_password)
    server.sendmail(sender_email, receiver_email, message)

Let’s explain what is happening here:

  1. Import smtplib and ssl libraries. The smtplib library defines an SMTP client session object that can be used to send email. The ssl library uses the OpenSSL library and provides access to Transport Layer Security (TLS) encryption and peer authentication facilities.
  2. We define the sender_email and receiver_email. The values used in the above code are for demonstration only, you will need to replace these values with valid email addresses.
  3. We define a simple email message as message.
  4. We define port as 465. Port number 465 is the default port for SMTP over SSL or SMTPS.
  5. We define app_password which will prompt the user at the terminal/console to input the 16-character app password we generated earlier.
  6. The create_default_context() method returns a new SSLContext object with default settings for the given purpose. We will use this to create the SMTP session.
  7. We create our secure SMTP session. The SMTP_SSL() method encapsulates an SMTP connection as server. Since we are using the Google SMTP server we must supply smtp.gmail.com for the host parameter. Then we supply the port and then the context that we specified earlier.
  8. The login method logs into an SMTP server that requires authentication. We supply the GMAIL email address account that was used to generate the app password along with the app_password itself.
  9. The sendmail() method is what will send our mail message. It accepts the sender_email, receiver_email and message parameters.

When we execute this script we will be prompted for the app_password at the console/command line/shell:

Enter the App Password When Prompted

When we type it in (without spaces) the script should execute without error. If you supply the wrong app_password you will get the following message:

smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials g12sm7812946qtq.92 - gsmtp')

If all goes well, you should see the email message in the inbox of the email address specified in the receiver_email.

python send email smtp
Success!

NOTE: In testing this script, a GMAIL address was used for both sender_email and receiver_email, also DO NOT SAVE YOUR APP PASSWORD WITH YOUR SCRIPT. Keep it safe and secure.

Thanks for reading. Good luck! Check out another great Python Tutorial on AES Encryption. 👌👌👌

Tags: smtpssl
Previous Post

PYTHON RSTRIP

Next Post

How To Defend Yourself Against False Accusations

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
Manage options
{title} {title} {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
Manage options
{title} {title} {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy