Python
Gmail
Email Automation
SMTP
Programming Tutorial

How to send an email with Gmail as provider using Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Python can send mail through Gmail, but the transport details matter. The simplest path is SMTP with smtp.gmail.com, TLS, and an app password when the account supports that flow. For more controlled production integrations, Gmail API access with OAuth2 is often the better long-term design.

Send Mail with SMTP and smtplib

Python's standard library already includes what you need for a basic email send. Use EmailMessage to build the message and smtplib.SMTP_SSL for a secure connection.

python
1import os
2import smtplib
3from email.message import EmailMessage
4
5
6sender = os.environ["GMAIL_ADDRESS"]
7app_password = os.environ["GMAIL_APP_PASSWORD"]
8
9message = EmailMessage()
10message["Subject"] = "Test message"
11message["From"] = sender
12message["To"] = "[email protected]"
13message.set_content("This email was sent from Python through Gmail SMTP.")
14
15with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
16    smtp.login(sender, app_password)
17    smtp.send_message(message)

This is the cleanest baseline example for a script or internal tool. Keep credentials out of source code and load them from environment variables or a secret manager.

Understand Authentication

The hard part is rarely the Python code. It is account authentication.

For accounts where app passwords are supported, the usual pattern is:

  • enable two-step verification on the account
  • generate an app password
  • use the app password in smtp.login

If your organization requires OAuth instead, or if app-password flows are restricted by policy, use Gmail API or OAuth-based SMTP access instead of trying to force a normal account password through SMTP.

That distinction matters because Gmail no longer treats direct username plus standard password authentication as a generally reliable approach for third-party apps.

Add Attachments Safely

Sending a file is only a small extension of the same pattern.

python
1import os
2import smtplib
3from email.message import EmailMessage
4
5
6sender = os.environ["GMAIL_ADDRESS"]
7app_password = os.environ["GMAIL_APP_PASSWORD"]
8
9message = EmailMessage()
10message["Subject"] = "Monthly report"
11message["From"] = sender
12message["To"] = "[email protected]"
13message.set_content("Attached is the latest report.")
14
15with open("report.txt", "rb") as f:
16    message.add_attachment(
17        f.read(),
18        maintype="text",
19        subtype="plain",
20        filename="report.txt",
21    )
22
23with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
24    smtp.login(sender, app_password)
25    smtp.send_message(message)

EmailMessage handles MIME generation for you, which is far safer than manually composing multipart email text.

When to Use the Gmail API Instead

SMTP is a good fit for straightforward outbound mail. If you need stronger account integration, mailbox access, label management, or organization-approved OAuth flows, the Gmail API is a better choice.

That does require Google Cloud setup, OAuth consent configuration, and token management, so it is heavier than SMTP. The tradeoff is that authentication and permissions are clearer and more aligned with Google's current platform direction.

Operational Considerations

Email sending also includes non-code concerns:

  • rate limits
  • spam filtering
  • domain authentication such as SPF and DKIM for organizational mail
  • retry behavior for transient failures

For a one-off script, those may not matter much. For alerts, customer emails, or business workflows, they matter a lot. Gmail is convenient, but it is not a full transactional email platform.

Common Pitfalls

  • Using your normal account password instead of an app password or approved OAuth flow.
  • Hard-coding Gmail credentials directly in Python source files.
  • Building MIME messages by hand instead of using EmailMessage.
  • Ignoring Gmail send limits and treating the account like a bulk email service.
  • Using Gmail SMTP for production application mail when a dedicated transactional provider would be more appropriate.

Summary

  • Python can send mail through Gmail with smtplib and EmailMessage.
  • 'smtp.gmail.com with SSL on port 465 is a common baseline for simple scripts.'
  • Authentication is the main issue, not the SMTP code itself.
  • Use app passwords where supported, or move to OAuth or the Gmail API when policy requires it.
  • For serious application mail, evaluate whether Gmail is the right provider at all.

Course illustration
Course illustration

All Rights Reserved.