Home › Blog › Export Gmail with Python

Export Gmail with Python: A Gmail API Script for CSV (2026 Quotas)

Published November 23, 2026 · 19 min read
Export formats
Developers
Gmail Exporter Guide
To export Gmail with Python: create a Google Cloud project, enable the Gmail API, create a Desktop app OAuth client, and authorize the read-only scope gmail.readonly. Then page through messages.list (500 IDs per call) and fetch each message with messages.get and format=metadata, writing the headers to CSV. In 2026 that call costs 20 quota units, and each user gets 6,000 units a minute, so the ceiling is about 300 messages a minute. Bodies (full or raw) cost 60 units, a third of that speed.

Most Gmail API tutorials were written against older quota numbers and stop at "print the subject of ten emails". This guide gives you a complete script: search query, pagination, a quota budget, retries with exponential backoff, a resumable CSV and an option that makes the file safe to open in Excel. It also shows what an export of 10,000 or 100,000 messages costs under the limits Google published for 2026.

Every limit and cost below comes from Google's developer documentation, checked on 31 October 2026 and linked where it's used. We checked the script with the official Python client library (google-api-python-client 2.201) against mocked API responses: pagination, a 429, a rate-limit 403, a deleted message, a resumed run and the request URLs it builds. Run it on a test account first, as you would any code that touches a mailbox.

What the script produces

One row per message, with the fields most people actually want in a spreadsheet or a pandas DataFrame:

ColumnComes fromNote
id, thread_idMessage id, threadIdStable keys. Use them to dedupe, resume or fetch the body later.
date_utcinternalDate (epoch ms)Google says this is "more reliable than the Date header" for normal received mail (Message resource)
from, to, cc, subjectHeaders requested with metadataHeadersRaw header text, for example Ana Ruiz <ana@acme.com>
date_headerThe Date headerWhat the sender's client wrote. It can be wrong or in any time zone.
labelslabelIdsSystem labels (INBOX, SENT, UNREAD…) plus label IDs for your own labels
size_bytessizeEstimateEstimated size, handy for finding heavy mail
snippetsnippet"A short part of the message text", if the API returns it

No body, no attachments. That's deliberate: metadata is a third of the quota cost of a full message and covers most reporting, CRM and audit jobs. The section on bodies and attachments adds them when you need them.

Setup in 10 minutes

This follows Google's own Python quickstart with one change that trips up most people using a personal @gmail.com address.

  1. Check Python. The quickstart requires Python 3.10.7 or later and pip.
  2. Create or pick a Google Cloud project and enable the Gmail API in it.
  3. Configure the consent screen under Google Auth platform › Branding: app name, support email, contact email.
  4. Choose the audience. The quickstart says "Internal", but Internal only exists for projects that belong to a Google Cloud Organization, in practice a Google Workspace domain (Manage app audience). With a personal Gmail account, choose External, leave the app in Testing, and add your own address under Test users (Configure the OAuth consent screen).
  5. Create the client: Google Auth platform › Clients › Create Client › Application type Desktop app. Download the JSON and save it as credentials.json next to the script.
  6. Install the libraries:
python3 -m pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

The first run opens a browser window. Because the app is unverified and in Testing, Google shows a warning before you can grant access; that's expected for your own project. The script then saves token.json so later runs don't ask again.

The 7-day catch in Testing mode

Google's Manage app audience page is explicit: in Testing, "authorizations by a test user will expire seven days from the time of consent", and so does the refresh token. Testing projects are also limited to 100 test users. So if a scheduled export starts failing on day eight, the code isn't broken: the token expired. The script catches the failed refresh and opens the consent flow again. For a job that runs unattended for months, you need a different setup, covered under scope and security below.

The script

Save this as export_gmail.py. It uses only the three Google libraries plus the standard library.

#!/usr/bin/env python3
"""Export Gmail message metadata to CSV with the Gmail API (read-only).

Usage:
  python3 export_gmail.py --query "after:2026/01/01 label:clients" --out clients.csv
"""
import argparse
import csv
import os
import random
import sys
import time
from datetime import datetime, timezone

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]
HEADERS = ["From", "To", "Cc", "Subject", "Date"]
COST_LIST = 5    # quota units per messages.list call
COST_GET = 20    # quota units per messages.get (format=metadata)
FIELDS = ["id", "thread_id", "date_utc", "from", "to", "cc",
          "subject", "date_header", "labels", "size_bytes", "snippet"]


def get_service():
    creds = None
    if os.path.exists("token.json"):
        creds = Credentials.from_authorized_user_file("token.json", SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            try:
                creds.refresh(Request())
            except Exception:  # e.g. refresh token expired after 7 days in Testing
                creds = None
        if not creds or not creds.valid:
            flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
            creds = flow.run_local_server(port=0)
        with open("token.json", "w") as f:
            f.write(creds.to_json())
    return build("gmail", "v1", credentials=creds, cache_discovery=False)


class Budget:
    """Never spend more than `per_minute` quota units in any rolling 60 s."""

    def __init__(self, per_minute):
        self.per_minute = per_minute
        self.log = []  # (timestamp, units)

    def spend(self, units):
        while True:
            now = time.monotonic()
            self.log = [(t, u) for t, u in self.log if now - t < 60]
            if sum(u for _, u in self.log) + units <= self.per_minute:
                self.log.append((now, units))
                return
            time.sleep(max(0.05, 60 - (now - self.log[0][0])))


def is_retryable(err):
    status = err.resp.status
    body = (err.content or b"").decode("utf-8", "ignore").lower()
    return status in (429, 500, 502, 503, 504) or (
        status == 403 and "ratelimitexceeded" in body)


def call(request, budget, units, max_tries=8):
    """Execute one API request with the unit budget and truncated exponential backoff."""
    for attempt in range(max_tries):
        budget.spend(units)
        try:
            return request.execute()
        except HttpError as err:
            if not is_retryable(err) or attempt == max_tries - 1:
                raise
            wait = min(2 ** attempt + random.random(), 64)
            print(f"  HTTP {err.resp.status}, retrying in {wait:.1f}s", file=sys.stderr)
            time.sleep(wait)


def list_ids(service, budget, query, limit=None):
    ids, token = [], None
    while True:
        resp = call(service.users().messages().list(
            userId="me", q=query, maxResults=500, pageToken=token), budget, COST_LIST)
        ids += [m["id"] for m in resp.get("messages", [])]
        token = resp.get("nextPageToken")
        if not token or (limit and len(ids) >= limit):
            return ids[:limit] if limit else ids


def fetch(service, budget, msg_id):
    req = service.users().messages().get(
        userId="me", id=msg_id, format="metadata", metadataHeaders=HEADERS,
        fields="id,threadId,labelIds,snippet,internalDate,sizeEstimate,payload/headers")
    try:
        return call(req, budget, COST_GET)
    except HttpError as err:
        if err.resp.status == 404:  # deleted between list and get
            return None
        raise


def excel_safe(value):
    """Stop spreadsheet apps from running a cell that starts like a formula."""
    return "'" + value if value[:1] in ("=", "+", "-", "@") else value


def to_row(msg, safe):
    h = {x["name"].lower(): x["value"] for x in msg.get("payload", {}).get("headers", [])}
    ts = int(msg.get("internalDate", 0)) / 1000
    row = {
        "id": msg["id"],
        "thread_id": msg.get("threadId", ""),
        "date_utc": datetime.fromtimestamp(ts, timezone.utc).strftime("%Y-%m-%d %H:%M:%S"),
        "from": h.get("from", ""),
        "to": h.get("to", ""),
        "cc": h.get("cc", ""),
        "subject": h.get("subject", ""),
        "date_header": h.get("date", ""),
        "labels": ";".join(msg.get("labelIds", [])),
        "size_bytes": msg.get("sizeEstimate", ""),
        "snippet": msg.get("snippet", ""),
    }
    if safe:
        for k in ("from", "to", "cc", "subject", "snippet"):
            row[k] = excel_safe(row[k])
    return row


def already_exported(path):
    if not os.path.exists(path):
        return set()
    with open(path, newline="", encoding="utf-8-sig") as f:
        return {r["id"] for r in csv.DictReader(f)}


def main():
    ap = argparse.ArgumentParser(description="Export Gmail metadata to CSV")
    ap.add_argument("--query", default="", help="Gmail search, e.g. 'from:bank.com after:2026/01/01'")
    ap.add_argument("--out", default="gmail_export.csv")
    ap.add_argument("--limit", type=int, default=None, help="stop after N messages")
    ap.add_argument("--units-per-minute", type=int, default=5400,
                    help="stay under the 6,000 units/min per-user limit")
    ap.add_argument("--excel-safe", action="store_true",
                    help="prefix cells starting with = + - @ with an apostrophe")
    args = ap.parse_args()

    service = get_service()
    budget = Budget(args.units_per_minute)
    ids = list_ids(service, budget, args.query, args.limit)
    done = already_exported(args.out)
    todo = [i for i in ids if i not in done]
    per_min = args.units_per_minute // COST_GET
    print(f"{len(ids)} matched, {len(done)} already in {args.out}, {len(todo)} to fetch "
          f"(~{len(todo) / per_min:.0f} min at {per_min} messages/min)")

    new_file = not os.path.exists(args.out)
    with open(args.out, "a", newline="", encoding="utf-8-sig") as f:
        writer = csv.DictWriter(f, fieldnames=FIELDS)
        if new_file:
            writer.writeheader()
        for n, msg_id in enumerate(todo, 1):
            msg = fetch(service, budget, msg_id)
            if msg:
                writer.writerow(to_row(msg, args.excel_safe))
            if n % 100 == 0:
                f.flush()
                print(f"  {n}/{len(todo)}")
    print(f"Done: {args.out}")


if __name__ == "__main__":
    main()

How it works, in five decisions

Running it

# everything from one client this year
python3 export_gmail.py --query "from:@acme.com after:2026/01/01" --out acme-2026.csv

# a label, capped at 2,000 messages, safe to open in Excel
python3 export_gmail.py --query "label:invoices" --limit 2000 --excel-safe --out invoices.csv

# interrupted? run the same command again: ids already in the CSV are skipped
python3 export_gmail.py --query "label:invoices" --excel-safe --out invoices.csv

The --excel-safe flag puts an apostrophe in front of any cell that begins with =, +, - or @. Email subjects and snippets are written by strangers, and a spreadsheet app can treat a cell that starts that way as a formula. If the file feeds code rather than a person, leave the flag off and keep the raw text.

Gmail API quotas in 2026: what an export really costs

Google changed the Gmail API limits on 1 May 2026. Its Gmail API usage limits page says projects that used the API between November 2025 and April 2026 "will continue with their previously set usage quotas", while projects created on or after 1 May 2026 get the new ones. Google's Google Workspace standardized model for agent tools and APIs page adds that the existing quotas "will remain unchanged for at least 60 days", so don't count on old numbers lasting. If you create a project today, these are your numbers:

LimitValueWhat it means for an export
Per minute per project1,200,000 quota unitsOnly matters if many users run your app at once
Per minute per user per project6,000 quota unitsThe real ceiling for a one-mailbox export
Daily billing threshold, per project80,000,000 quota unitsUsage under it isn't billed. You can't ask for it to be raised.
Recipients per message (sending)500Not relevant to reading, listed for completeness

Source: Google Gmail API usage limits. Last verified 31 Oct 2026.

The method costs that matter for exporting:

MethodQuota unitsUsed for
messages.list5Up to 500 message IDs per call
messages.get (minimal, metadata)20Headers, labels, dates
messages.get (full, raw, html)60Bodies, MIME structure, .eml files
messages.attachments.get20One attachment's bytes
threads.list10Thread IDs
threads.get40 (120 when full)Every message in a thread in one call
history.list2Changes since your last export
getProfile1Mailbox address and totals

Source: Google Gmail API usage limits, per-method quota usage. Last verified 31 Oct 2026.

The arithmetic, by mailbox size

Divide the per-user limit by the cost per call. 6,000 ÷ 20 = 300 metadata fetches a minute at most; 6,000 ÷ 60 = 100 full messages a minute. Listing is a rounding error: 100,000 IDs take 200 list calls, or 1,000 units. These are floors set by the quota, not measured run times; network latency can only make them longer.

MessagesUnits, metadata (20 each)Minimum time, metadataUnits, full or raw (60 each)Minimum time, full
1,00020,000about 3 min 20 s60,000about 10 min
10,000200,000about 33 min600,000about 1 h 40 min
50,0001,000,000about 2 h 45 min3,000,000about 8 h 20 min
100,0002,000,000about 5 h 35 min6,000,000about 16 h 40 min

Calculated from the 6,000 units/min per-user limit, including the list calls. The script's default budget of 5,400 units/min adds about 11%. Last verified 31 Oct 2026.

Will you hit the billing threshold?

Not from one mailbox. One user at the full per-user rate for 24 hours spends 6,000 × 1,440 = 8,640,000 units, about a ninth of the 80,000,000-unit daily threshold. You'd need roughly ten mailboxes exporting flat out all day in the same project to reach it. For an internal tool that exports many staff mailboxes, though, it's a real planning number: 80,000,000 ÷ 20 is 4,000,000 metadata fetches per project per day.

Google hasn't published prices yet. The quota page says "Google will share full billing details later in 2026 with at least 90 days' notice before any changes take effect", and the Google Workspace standardized model for agent tools and APIs page says that, after that notice, usage above the standard daily thresholds "will generate charges on your Google Cloud bill" and quota increase requests will require billing to be enabled. If you build something that runs at scale, watch that page.

Why batching won't make it faster

Batch requests save HTTP connections, not quota. Google's Batching requests guide says "a set of n requests batched together counts toward your usage limit as n requests, not as one request", caps a batch at 100 calls and recommends no more than 50. Parallel threads don't help either: there's a per-user concurrent request limit that returns 429 "Too many concurrent requests for user" (Resolve errors). With the 2026 numbers, the unit budget is the bottleneck, so a simple sequential loop that never trips the limit finishes about as fast as an elaborate concurrent one that keeps backing off.

metadata vs full vs raw vs minimal

FormatWhat you getUnits per messageUse it for
minimalID and labels only, no headers or body20Label audits. Rarely worth it: metadata costs the same.
metadataID, labels and headers (only the ones you name with metadataHeaders)20CSV exports, contact lists, reporting
fullEverything, with the body parsed into the payload MIME tree60Reading text bodies, finding attachment IDs
rawThe whole RFC 2822 message as one base64url string60Archiving as .eml, legal copies, re-importing elsewhere

Source: Google Format enum and Gmail API usage limits. Last verified 31 Oct 2026.

Since minimal and metadata cost the same 20 units, always take metadata.

The thread trick for metadata

threads.get with format=metadata costs 40 units and returns every message in the thread. If your threads average more than two messages, that's cheaper per message than calling messages.get on each one. A three-message thread costs 40 units instead of 60, and a ten-message thread 40 instead of 200. Google's Synchronize clients with Gmail guide notes you can do a full sync with the thread methods, which "might be advantageous if your app primarily works with threads or only requires message metadata". The swap is small:

t = service.users().threads().get(
    userId="me", id=thread_id, format="metadata",
    metadataHeaders=["From", "To", "Subject", "Date"]).execute()   # 40 units
for msg in t["messages"]:
    ...  # same headers as messages.get, one call for the whole thread

Use threads.list (10 units per page) instead of messages.list. Check your own ratio first: an inbox full of newsletters averages close to one message per thread, and there the trick doesn't pay.

Bodies, attachments and .eml files

When you need the content, fetch per message, only for the subset you care about. These two helpers reuse call() and the budget from the main script. Save them as extras.py in the same folder.

import base64
import os

from export_gmail import call

COST_FULL = 60      # messages.get with format=full or raw
COST_ATTACH = 20    # messages.attachments.get


def b64(data):
    return base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))


def walk(part):
    yield part
    for child in part.get("parts", []):
        yield from walk(child)


def save_attachments(service, budget, msg_id, folder="attachments"):
    msg = call(service.users().messages().get(
        userId="me", id=msg_id, format="full"), budget, COST_FULL)
    os.makedirs(folder, exist_ok=True)
    for part in walk(msg["payload"]):
        name, body = part.get("filename"), part.get("body", {})
        if not name:
            continue
        if "attachmentId" in body:
            data = call(service.users().messages().attachments().get(
                userId="me", messageId=msg_id, id=body["attachmentId"]),
                budget, COST_ATTACH)["data"]
        else:
            data = body.get("data", "")
        path = os.path.join(folder, f"{msg_id}_{os.path.basename(name)}")
        with open(path, "wb") as f:
            f.write(b64(data))


def save_eml(service, budget, msg_id, folder="eml"):
    msg = call(service.users().messages().get(
        userId="me", id=msg_id, format="raw"), budget, COST_FULL)
    os.makedirs(folder, exist_ok=True)
    with open(os.path.join(folder, f"{msg_id}.eml"), "wb") as f:
        f.write(b64(msg["raw"]))

Budget it: an email with two large attachments costs 60 + 20 + 20 = 100 units, so the per-user limit allows about 60 of those a minute.

Incremental exports with history.list

Running the full export every night re-fetches everything. The cheaper pattern from Google's Synchronize clients with Gmail guide: after a full export, store the historyId of the newest message. Next time, call history.list (2 units) with startHistoryId and you get only the messages added, deleted or relabeled since.

The limit to plan for: history records "are typically available for at least one week and often longer", but the period "might be significantly shorter". If the ID is too old, the API returns HTTP 404 and you must do a full sync again (users.history.list). A daily job is safe; a monthly one should expect to fall back to a full export. Because the script above already skips IDs it has written, that fallback costs list calls, not a re-download.

Errors you'll actually see

ErrorUsual causeWhat to do
403 rateLimitExceeded / userRateLimitExceededOver the per-minute unit budgetExponential backoff (the script does this) or a lower --units-per-minute
429 "Too many concurrent requests for user"Parallel calls or big batches on one mailboxFewer parallel requests; smaller batches
429 "User-rate limit exceeded"Per-user bandwidth limit, which Google says is equal to IMAP's and shared by all API clients for that userBack off; it can last "multiple hours" after daily limits are exceeded
404 on messages.getMessage deleted after it was listedSkip it (the script does)
404 on history.liststartHistoryId too oldFull sync
500, 502, 503, 504Server-side errorsRetry with backoff
Token refresh fails, typically invalid_grantTesting-mode authorization expired after 7 days, or access was revokedDelete token.json and authorize again

Source: Google Resolve errors and Manage app audience. Last verified 31 Oct 2026.

Google adds that per-user limits can't be increased; the documented ways around them are retrying failed requests or "splitting processing across multiple Gmail accounts".

Scope and security

Ask for the narrowest scope that does the job. Google classes every scope that can read mail as restricted (Choose Gmail API scopes):

ScopeGrantsClassFor an export
gmail.metadataLabels and headers, no bodyRestrictedTempting, but messages.list can't take a q search with it, and full/raw are blocked. You'd export everything or filter by label only.
gmail.readonlyRead messages and settingsRestrictedThe right choice: search plus read, no write
gmail.modifyRead, write, trashRestrictedOnly if you also label or archive what you export
https://mail.google.com/Full access, including permanent deleteRestrictedNever for an export

Source: Google Choose Gmail API scopes and users.messages.list. Last verified 31 Oct 2026.

What that classification means in practice:

When not to write code

Python is the right tool when the export feeds a pipeline, runs on a schedule or needs custom logic. For a one-off it's often the slowest route once you count setup and the quota.

MethodSetupBest forLimits
Python + Gmail API (this guide)Cloud project, OAuth, codePipelines, scheduled jobs, custom fields, incremental sync20-60 units per message; 7-day tokens in Testing
Apps Script to Google SheetsPaste a script in the browserLightweight jobs that end in a SheetApps Script execution and service quotas
Google TakeoutNoneA full MBOX backup of the whole mailboxWhole labels only, no search filter, no CSV; then convert MBOX to CSV
Gmail Exporter (Chrome extension)InstallExporting a search or label to CSV, Excel or JSON in a few clicksRuns locally in your Gmail tab. CSV is free; dates, Excel and JSON need a one-time paid plan.

If the destination is a database, our guide to exporting Gmail to SQLite covers schema and indexing. If you already have a JSON file and only need to parse it, start with exporting Gmail to JSON. For header fields beyond From/To/Subject, such as Message-ID or Received, see exporting Gmail headers; add them to the HEADERS list in the script.

Don't need code? Export a search in one click

Gmail Exporter turns any Gmail search or label into a CSV in your browser: no Cloud project, no OAuth, no quota maths. CSV is free; dates, Excel and JSON come with a one-time Pro plan.

Add to Chrome — It's Free

Frequently asked questions

How do I export Gmail emails with Python?

Enable the Gmail API in a Google Cloud project, create a Desktop app OAuth client, authorize the gmail.readonly scope, list message IDs with messages.list (with a Gmail search in q), fetch each with messages.get using format=metadata, and write the headers to CSV with the csv module. The script in this guide does all of that with pagination, retries and resume.

How many quota units does messages.get cost in 2026?

20 units with format minimal or metadata, and 60 units when the format is full, raw or html, according to Google's Gmail API usage limits page. messages.list costs 5 units and messages.attachments.get costs 20. Projects that used the API between November 2025 and April 2026 kept their previous quotas for now.

How many emails per minute can the Gmail API read?

Each user gets 6,000 quota units per minute per project. At 20 units per metadata fetch that's at most 300 messages a minute; at 60 units for full or raw messages it's 100 a minute. A 10,000-message metadata export therefore takes at least about 33 minutes.

Will the Gmail API start charging money?

Google says usage under the daily billing threshold of 80,000,000 quota units per project isn't billed, and that it will share full billing details later in 2026 with at least 90 days' notice. One mailbox can't reach the threshold on its own: at the full per-user rate it uses about 8.6 million units a day.

Why does my Gmail API token stop working after 7 days?

If your OAuth consent screen is External with a publishing status of Testing, Google expires test users' authorizations, including refresh tokens, seven days after consent. Delete token.json and authorize again, or move to a setup that suits long-running jobs.

Do I need Google verification to use the Gmail API for my own account?

No. Google's restricted scope verification page lists personal use as an exception: when you're the only user of the app or the users are a few people you know personally. You'll see an unverified app warning, which you can pass for your own project.

Which scope should I use to export Gmail?

gmail.readonly. gmail.metadata looks narrower, but Google documents that messages.list can't use the q search parameter with it and that full and raw formats are blocked. Avoid gmail.modify and https://mail.google.com/ for exports: they allow changes and deletion.

Does batching Gmail API requests save quota?

No. Google's batching guide says n batched requests count as n requests toward your usage limit. Batching saves HTTP overhead, is capped at 100 calls per batch and Google recommends 50 or fewer, because larger batches are likely to trigger rate limiting.