Introduction
Today, we'd be looking at an interesting topic, Sending Emails from your Gmail account using Python. How does that sound? Python is such a powerful programming language.
We are going to use the SMTP(Simple Mail Transfer Protocol) library to implement this. Python provides smtplib module which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.
The SMTP object has an instance method which is called Sendmail, this is used for mailing messages. It has three parameters which are;
- The sender − A string with the address of the sender.
- The receivers − A list of strings, one for each recipient.
- The message − A message as a string formatted as specified in the various RFCs.
Note: When sending emails with Python, you must ensure your SMTP connection is encrypted, so your message and login credentials are not easily accessed by others. SSL (Secure Sockets Layer) and TLS (Transport Layer Security) are two protocols that can be used to encrypt an SMTP connection.
Let's dive into each of these protocols;
Understanding SMTP
SMTP (Simple Mail Transfer Protocol) is the standard protocol used for sending emails across the Internet. When you send an email, your email client communicates with an SMTP server, which then routes the message to the recipient's mail server.
Gmail provides an SMTP server at smtp.gmail.com that you can use to send emails programmatically. Python's built-in smtplib module makes it straightforward to connect to this server and send messages.
The typical email delivery flow looks like this:
There are two main ways to secure your SMTP connection: SSL and TLS. Both encrypt the communication between your script and the Gmail server, but they work slightly differently.
SMTP with SSL
Here is a demonstration of how to create a secure connection with Gmail's SMTP server using SSL Protocol.
import smtplib, ssl
port = 465 # For SSL
password = input("type-your-password-here")
# using a secure SSL context
context = ssl.create_default_context()
#this will be used to send our email
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login("[email protected]", password)
With SSL, the connection is encrypted from the very start. Port 465 is the standard port for SMTP over SSL. The ssl.create_default_context() method loads the system's trusted CA certificates to verify the server's identity.
SMTP with TLS
Here is a demonstration of how to create a secure connection with Gmail's SMTP server using TLS Protocol.
import smtplib, ssl
smtp_server = "smtp.gmail.com" #name of smtp server
port = 587 # For starttls
sender_email = "[email protected]" #put in your email address here
password = input("type-your-password-here ")
# we use a secure SSL context
context = ssl.create_default_context()
# Now we try to log in to the server and send email
try:
server = smtplib.SMTP(smtp_server, port)
server.ehlo() # Can be omitted
server.starttls(context=context) # Secure the connection using the tls protocol
server.login(sender_email, password)
except Exception as e:
print(e)
finally:
server.quit()
Now, we've seen how to create a secure connection using either of the protocols listed above. The next thing to do is to put an email message which will be in plain text format for our demonstration here.
Sending Email In Simple Text Format using SSL Protocol
Here, we will pass in our email body in plain text format and then replicate the same code we used earlier for creating an SSL secured connection.
import smtplib, ssl
port = 465 # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]" #put in your email address here
receiver_email = "[email protected]" #put in your receiver email address here
password = input("type-your-password-here")
message = """\
Subject: Hi there
This message is to notify you my friend...."""
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
Sending Email in HTML Format
You might be wondering if it's possible to send your text in a more modified or beautified format whereby your email content is bolded, italicized, contain images, and so on. Python email.mime module can help in handling that. An example code is shown below on how we have both plain text and that of Html format. In this code, we will use the MIMEText from email.mime module to convert both plain text and that of Html format into MIME object, before proceeding to attach as our message body.
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = input("type-your-password-here")
message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email
#Create the plain-text and HTML version of your message
text = """\
Hello,
How are you?
"""
html = """\
<html>
<body>
<p>Hello<br>
How are you?
</p>
</body>
</html>
"""
# we then convert these into plain/html MIMEText objects
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
#You then add the HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(part1)
message.attach(part2)
#create secure connection and send your email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(
sender_email, receiver_email, message.as_string()
)
MIME Email Structure
When you send an HTML email using Python, the message is structured using the MIME (Multipurpose Internet Mail Extensions) standard. This allows a single email to contain multiple content types. Here's how the structure works:
The MIMEMultipart("alternative") container holds both a plain text version and an HTML version of your message. The email client will try to render the last attached part first (HTML), falling back to plain text if HTML is not supported.
The key components of a MIME email are:
- Headers − Subject, From, To, and content type metadata.
- Plain Text part − A fallback version for email clients that don't render HTML.
- HTML part − The rich-formatted version with styling, images, and layout.
When both parts are attached with message.attach(), the email client will automatically choose the best format to display. Most modern clients will render the HTML version.
Security Best Practices
When sending emails programmatically, security should be a top priority. Here are the essential practices to follow:
Use App Passwords instead of your main password. Gmail requires you to generate an App Password when using third-party applications. Go to your Google Account security settings and create one specifically for your Python script.
Always use SSL or TLS. Never send emails over an unencrypted connection. Both SMTP_SSL (port 465) and starttls() (port 587) encrypt your credentials and message content during transmission.
Never hardcode credentials. Store your email and password in environment variables or a secure vault. Use os.environ.get("EMAIL_PASSWORD") instead of placing passwords directly in your source code.
Handle errors gracefully. Wrap your SMTP operations in try/except blocks. Network issues, authentication failures, and rate limits can all cause exceptions that should be caught and logged properly.
Conclusion
And that's a wrap. Follow the steps above to start sending emails from your Gmail using Python. For questions and observations, use the comments section below. Follow us for more informative posts. Thanks for reading.