Skip to content

Automating Email with Python and the Gmail API

Send personalized emails from templates using the Gmail API and OAuth 2.0, with logging and sensible limits so automation stays helpful, not spammy.

Muhammad Yasir

@YasirAwan4831

Published 2 min read

Automating Email with Python and the Gmail API

On this page

Repetitive email, such as follow-ups, reports and confirmations, is a perfect candidate for automation. Python and the Gmail API give you a clean, secure way to do it without sharing your password with a script.

Why the Gmail API instead of SMTP passwords

Gmail supports sending through the API with OAuth 2.0. Your script receives a token with limited permissions, which you can revoke at any time, instead of holding your account password. For a send-only script, request the narrowest scope that allows sending.

The overall flow

  1. Create a project in the Google Cloud console and enable the Gmail API.

  2. Create OAuth credentials for a desktop application and download the client file.

  3. Run the authorization flow once; store the resulting token locally and keep it out of version control.

  4. Build a message, encode it and call the send endpoint.

Templates and personalization

Separate content from code. Keep an HTML template with placeholders and fill them from your data (a CSV or database). This keeps messages consistent and easy to edit by non-developers.

from string import Template

template = Template("""
<p>Hi $name,</p>
<p>Thanks for your interest in $topic. Here is the summary you asked for.</p>
""")

body = template.substitute(name="Ayesha", topic="data analysis")

Build the message safely

Use Python's standard email package to construct the message, then base64url-encode it for the API. Setting both a plain-text and an HTML part improves compatibility.

Logging and limits

  • Log recipient, time and result for every send so you can audit what happened.

  • Add a short delay between messages and respect Gmail sending limits.

  • Add a dry-run mode that prints messages instead of sending them.

  • Include a clear way for recipients to opt out of recurring mail.

Keep it responsible

Automation should save people time, not flood their inbox. Send only to people who expect to hear from you, personalize honestly, and keep a human in the loop for anything sensitive.

Enjoyed this article?

Share it with someone who might find it useful.