How to Send Emails with Python: Beginner Tutorial (Gmail + SMTP)

Python’s smtplib can connect to an SMTP server, but modern email providers generally require an app password or OAuth rather than your normal account password. Enable multi-factor authentication and follow the provider’s current SMTP documentation.

import os
import smtplib
from email.message import EmailMessage

message = EmailMessage()
message["Subject"] = "Test message"
message["From"] = os.environ["EMAIL_USER"]
message["To"] = os.environ["EMAIL_TO"]
message.set_content("This message was sent from Python.")

with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
    server.login(os.environ["EMAIL_USER"], os.environ["EMAIL_APP_PASSWORD"])
    server.send_message(message)

Never hard-code passwords or commit them to Git. Use environment variables locally and a secret manager in deployment. Add timeouts, catch authentication and connection errors, and avoid sending repeated messages when a job restarts.

For HTML mail, use add_alternative() and provide a plain-text version. For newsletters, use a dedicated email service with unsubscribe handling, bounce processing, and delivery monitoring rather than a personal mailbox.

Test with your own address first, then verify sender authentication and provider limits before sending to customers.

Leave a Comment

Scroll to Top