How to Send Emails Using Python and Gmail: A Comprehensive Guide

O

Ohidur Rahman Bappy

MAR 22, 2025

Authenticating with Gmail

Before sending emails through Gmail using SMTP with Python, authentication is crucial. Gmail requires explicit permission to allow connections via SMTP, which is considered less secure.

Google requires these steps because your application must store your plain-text password, a less secure approach compared to OAuth's revocable tokens.

For many other email providers, the extra steps outlined here might not be necessary.

  1. Allow Less Secure Apps: To permit access by less secure apps, follow the instructions detailed here: Allowing less secure apps to access your account

  2. App-Specific Passwords: If two-factor authentication (2FA) is enabled, create an app-specific password: Sign in using App Passwords

  3. Resolve SMTPAuthenticationError: If you encounter an error code 534, try the following: Display Unlock Captcha

    Sometimes there is a short delay after enabling less secure apps before the Captcha unlock works.

Here's how to set up an SMTP connection using Python:

import smtplib

gmail_user = 'you@gmail.com'
gmail_password = 'P@ssword!'

try:
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_password)
except:
    print('Something went wrong...')

Sending the Email

With SMTP configured and authenticated, you can send an email using Python and Gmail. Utilize the server object to call the .sendmail() method, as shown below:

import smtplib

gmail_user = 'you@gmail.com'
gmail_password = 'P@ssword!'

sent_from = gmail_user
to = ['me@gmail.com', 'bill@gmail.com']
subject = 'OMG Super Important Message'
body = 'Hey, what's up?\n\n- You'

email_text = """\
From: %s
To: %s
Subject: %s

%s
""" % (sent_from, ", ".join(to), subject, body)

try:
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_password)
    server.sendmail(sent_from, to, email_text)
    server.close()

    print('Email sent!')
except:
    print('Something went wrong...')

Conclusion

While additional authorization steps are required with Gmail (such as allowing less secure apps), this Python code is applicable for other email providers supporting SMTP, provided you configure the correct server address and port.

If you encounter SMTP restrictions from other providers or have tips on programmatic email use cases, share your insights in the comments!