The Gmail API is Google's REST API for reading, sending, searching and organising email in a Gmail or Google Workspace mailbox over HTTP, without IMAP or SMTP. Your app gets the mailbox owner's consent through OAuth 2.0, then calls resources such as messages, threads, drafts, labels and history, and can receive a push notification through Google Cloud Pub/Sub when the mailbox changes. Calls cost nothing below a daily threshold of 80 million quota units per Cloud project. Before any of that works for other people, the app has to pick the narrowest scope it can and, for most mailbox access, pass Google's verification.
This guide covers setup, scopes, sending and threading, search, push notifications and the failures that show up in production, from Google's own documentation as read in November 2026. Quotas and daily sending limits have their own guide: Gmail sending limits.
What can the Gmail API do?
Everything Gmail does with a mailbox, as REST resources. Each call costs quota units, which is what the per-minute limits count:
| Resource | What it does | Quota units per call |
|---|---|---|
| messages.send / drafts.send | Send an email you built as a MIME message | 100 |
| messages.list | Search a mailbox with Gmail's search syntax, returns IDs | 5 |
| messages.get | Read one message (minimal, metadata, full or raw) | 20, or 60 for full, raw or html |
| threads.get | Read a whole conversation | 40, or 120 for full |
| messages.batchModify | Add or remove labels on many messages | 50 |
| messages.attachments.get | Download an attachment | 20 |
| history.list | Changes since a known point in the mailbox history | 2 |
| watch | Push notifications through Pub/Sub | 100 |
| labels.list / labels.get | Read labels, Gmail's folders | 1 |
Since 1 May 2026, a new Cloud project gets 1,200,000 quota units a minute and 6,000 per user per minute. History is cheap and full reads are expensive: syncing a mailbox with history.list and reading only the new messages costs a fraction of listing and re-reading everything.
How do you set up the Gmail API?
Five steps in the Google Cloud console, all free:
- Create a Google Cloud project, or pick an existing one. Quotas and the billing threshold are counted per project.
- Enable the Gmail API in APIs and Services, Library.
- Configure the consent screen under Google Auth platform. Choose Internal if only accounts of your own Workspace organization will connect, External for anyone else, including personal Gmail accounts.
- Create an OAuth client ID. Google's Python quickstart uses a Desktop app client, downloaded as
credentials.json. A product that users connect from the web needs a Web application client with your redirect URI. - Install a client library. For Python:
python3 -m pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib.
Google's full Gmail API reference lists every method and parameter. The first run opens a browser for consent, and the quickstart saves the access and refresh tokens to token.json so later runs skip that step. Change the scopes and you have to delete token.json and consent again. An External app left in Testing status is fine for a prototype and wrong for anything else, because its refresh tokens die after 7 days and every user has to reconnect.
Which Gmail API scope do you need?
The narrowest one that does the job, because the scope decides how much review Google requires. Google sorts the Gmail scopes into three classes:
| Scope | Allows | Google's class |
|---|---|---|
| gmail.labels | Create and edit labels only | Non-sensitive |
| gmail.send | Send email, nothing else | Sensitive |
| gmail.readonly | Read all messages and settings | Restricted |
| gmail.compose | Create, read, update and send drafts and messages | Restricted |
| gmail.modify | Read, send and change labels, everything except permanent deletion | Restricted |
| gmail.metadata | Headers and labels without bodies | Restricted |
| gmail.insert / gmail.settings.basic / gmail.settings.sharing | Add messages, change settings | Restricted |
| https://mail.google.com/ | Full access, including permanent deletion, IMAP and SMTP | Restricted |
A public app using sensitive or restricted scopes must go through Google's verification. Restricted scopes add one more condition, in Google's words: "If you store restricted scope data on servers (or transmit), then you must go through a security assessment." That assessment is renewed every year. In practice, an app that only sends can live with gmail.send, while anything that reads replies from a server lands in the restricted class.
Two other routes skip the consent screen for users. Inside a Google Workspace domain, an admin can give a service account domain-wide delegation, so it acts for the organization's mailboxes without each person clicking through, which is how internal tools usually run. And IMAP or SMTP with OAuth (XOAUTH2) is possible, but it needs the full https://mail.google.com/ scope, which Google itself tells developers to move away from in favour of the narrower Gmail API scopes.
How do you send and reply in the same thread with the Gmail API?
You build a MIME message, encode it in base64url, and pass it as raw to users.messages.send. The basic send is shown step by step in our Gmail sending limits guide, so here is the case that trips people up: replying inside an existing conversation. Google's message reference sets three conditions for a message to join a thread. The threadId must be on the message you send, the References and In-Reply-To headers must follow RFC 2822, and the Subject headers must match.
import base64
from email.message import EmailMessage
from googleapiclient.discovery import build
service = build("gmail", "v1", credentials=creds) # creds from the OAuth flow
# Read only the headers we need: 20 quota units with format="metadata"
original = service.users().messages().get(
userId="me",
id=message_id,
format="metadata",
metadataHeaders=["Message-ID", "Subject", "References", "From"],
).execute()
headers = {h["name"].lower(): h["value"] for h in original["payload"]["headers"]}
reply = EmailMessage()
reply["To"] = headers["from"]
reply["Subject"] = headers["subject"] # the Subject headers must match
reply["In-Reply-To"] = headers["message-id"]
reply["References"] = (headers.get("references", "") + " " + headers["message-id"]).strip()
reply.set_content("Following up on my note below.")
raw = base64.urlsafe_b64encode(reply.as_bytes()).decode()
sent = service.users().messages().send(
userId="me",
body={"raw": raw, "threadId": original["threadId"]}, # 100 quota units
).execute()
print(sent["id"], sent["threadId"])Miss any one of the three and Gmail files the email as a new conversation instead of a reply. To attach a file, add it to the same EmailMessage before encoding, for example reply.add_attachment(data, maintype="application", subtype="pdf", filename="quote.pdf"), and the attachment travels inside the raw MIME message. A follow-up sequence therefore has to store the Message-ID of every email it sends, because that is what the next email references. And a send that returns 200 only means Gmail accepted the request: it still counts against the mailbox's daily sending limit, and it can still bounce.
How do you read and search emails with the Gmail API?
messages.list takes the same search syntax as the Gmail search box in its q parameter and returns message IDs, not messages. You then call messages.get on each ID, choosing the format that costs the least for what you need:
resp = service.users().messages().list(
userId="me",
q="from:jane@acme.com newer_than:7d",
maxResults=50,
).execute() # 5 quota units
for ref in resp.get("messages", []):
msg = service.users().messages().get(
userId="me", id=ref["id"], format="metadata"
).execute() # 20 quota units each
print(msg["snippet"])Results come in pages, with a nextPageToken to pass back for the next one. Fifty messages read in metadata format cost 1,005 units, against 3,005 in full format, so read bodies only when you use them. Gmail's labels play the role of folders, and a message can carry several at once, which is why INBOX is a label you filter on rather than a place.
How do you get new emails in real time with the Gmail API?
With push notifications. Polling messages.list every minute burns quota and still arrives late, so Google pushes a change notice to a Cloud Pub/Sub topic instead. Setting it up takes three steps:
- Create a Pub/Sub topic and a subscription, push to your HTTPS endpoint or pull.
- Grant publish rights on the topic to
gmail-api-push@system.gserviceaccount.com, the account Gmail publishes from. - Call watch for each mailbox:
resp = service.users().watch(
userId="me",
body={"topicName": "projects/my-project/topics/gmail-inbox", "labelIds": ["INBOX"]},
).execute() # 100 quota units
last_history_id = resp["historyId"] # store it; resp["expiration"] says when the watch endsA notification does not contain the email. It carries the mailbox address and a new historyId, encoded in base64url. Your handler calls history.list with the last historyId it stored as startHistoryId, reads the messages that were added, and stores the new historyId for next time.
Three rules from Google's push guide decide whether this keeps working. Call watch at least every 7 days or notifications stop, and Google recommends once a day. Each watched user gets at most one notification per second, and the extra ones are dropped, so a busy mailbox needs a periodic history.list as a safety net. And when the stored historyId is too old, history.list returns a 404 and the only fix is a full sync, listing and re-reading messages. History records are typically kept for at least a week.
What does the Gmail API cost?
Nothing for standard use. Google's usage limits page sets a threshold of 80 million quota units a day per project, below which there is no charge, and says that usage beyond its quota limits is planned to be billed later in 2026, with at least 90 days' notice. That is 800,000 sends a day per project before billing could start. Projects that used the API between November 2025 and April 2026 keep their previous quotas. Per-minute limits, sending limits and the error codes for each are in our Gmail sending limits guide.
The real costs are elsewhere: the verification and yearly security assessment for restricted scopes, and the engineering time to keep tokens, watches and history in sync for every connected mailbox.
What breaks in production?
Tokens that expire after a week. The symptom is every user disconnected seven days after connecting. The cause is an External consent screen left in Testing status. Publish the app, which for sensitive and restricted scopes means passing verification first.
A password change. Google revokes refresh tokens that carry Gmail scopes when the user changes their password. Your app sees invalid_grant on the next refresh and has to ask the person to connect again, so plan a reconnect flow from day one.
Too many connections from one account. Google allows 100 refresh tokens per Google account per OAuth client. The 101st silently invalidates the oldest, which bites test accounts and products that create a new token on every login instead of reusing the stored one.
An admin policy. In a Workspace domain, an admin can mark Gmail as restricted for third-party apps. The sign-in then fails with admin_policy_enforced, and only that admin can allow your app.
A watch that quietly ended. Notifications stop without an error when nobody renews the watch within 7 days. Renew daily on a schedule, and alert when a mailbox has had no notification for longer than usual.
A stale historyId. After downtime, history.list answers 404. Treat it as a signal to run a full sync for that mailbox, not as an error to retry.
Should you use the Gmail API directly or a provider?
It depends on whose mailboxes and how many:
| Your situation | What fits |
|---|---|
| Scripts on your own mailbox or your own organization's | The Gmail API directly, Internal consent screen or a service account |
| Your users' Gmail inside a CRM, helpdesk or AI assistant | The Gmail API with verification, or a mailbox API: Nylas, Unipile, EmailEngine |
| Outreach from many mailboxes, with caps, sequences and replies | An outreach API built for it |
Going direct costs nothing in fees but means one integration per provider: Microsoft 365 mailboxes need Microsoft Graph and their own limits, covered in our Outlook sending limits guide. The email API guide compares the three kinds of email API, and the EmailEngine review, Nylas pricing and Unipile review cover the mailbox APIs. The Microsoft side of the integration is walked through in our Outlook API guide.
Swarmhit sits in the third row. On the Smart API, a hosted connect link lets a person connect a Google mailbox by signing in on Google's own page or with a Google app password, and any other mailbox over IMAP, and the engine then handles daily caps per mailbox, threading, reply detection and bounce suppression, with email steps in the same sequence as LinkedIn and WhatsApp steps. On the Raw API, in early access, you connect Google mailboxes with your own OAuth app's tokens or a service app's delegated access, and call one endpoint per action, with Gmail's labels exposed as folders. Either way, every mailbox keeps Gmail's own daily sending limits, and the cold email infrastructure guide covers domains, DNS and warmup before you send.
FAQ
Does Gmail have an API?
Yes. The Gmail API is Google's REST API for Gmail and Google Workspace mailboxes: it reads, searches, sends and labels email, manages drafts and settings, and pushes mailbox changes through Cloud Pub/Sub. It is free for standard use, works with any language over HTTP, and has official client libraries for Python, Java, Node.js, Go and others. Access goes through OAuth consent from the mailbox owner.
Do you need an API key for the Gmail API?
No, not for mailbox data. Google says API keys are for anonymously accessing publicly available data, and a mailbox is private. Reading or sending someone's Gmail needs an OAuth client ID, with the user's consent, or inside a Google Workspace domain a service account with domain-wide delegation. That is why searches for a Gmail API key end in the credentials page of the Cloud console, where you create an OAuth client and download credentials.json.
Is the Gmail API free?
Yes, for standard use. Google charges nothing below a threshold of 80 million quota units a day per Cloud project and plans to bill usage beyond its quota limits later in 2026, with at least 90 days' notice. Sending costs 100 units, so the threshold is 800,000 sends a day per project. The costs that matter sooner are Google's verification and the yearly security assessment that restricted scopes require for public apps.
Can I use the Gmail API with a personal Gmail account?
Yes. A personal account connects through OAuth like any other, with an External consent screen. Keep the app in Testing status only for a prototype, because refresh tokens then expire after 7 days. Service accounts with domain-wide delegation work only inside a Google Workspace domain, where an admin grants them access, so they are not an option for personal Gmail accounts.
Does a Gmail API app need Google verification?
A public app that requests sensitive or restricted Gmail scopes must complete Google's verification. gmail.send is sensitive. gmail.readonly, gmail.modify, gmail.compose and the full mail.google.com scope are restricted, and an app that stores or transmits that data on its servers also needs a security assessment, renewed every year. An Internal app used only inside your own Workspace organization avoids the review.
What is the difference between the Gmail API and IMAP?
IMAP is the standard mail protocol and works with any provider, but with OAuth at Gmail it needs the full mail.google.com scope. The Gmail API is HTTP and JSON, offers narrower scopes such as gmail.send or gmail.readonly, works with labels natively, and can push changes through Pub/Sub instead of holding a connection open. Google recommends the Gmail API for apps that do not need full mailbox access.
How many emails can I send with the Gmail API?
The same as from Gmail itself, because the API enforces each account's daily sending limits: up to 500 emails a day on a personal Gmail account and 2,000 messages a day per user on paid Google Workspace, per Google's published limits. The API's own quota, 6,000 units per user per minute on new projects, allows about 60 sends a minute and is never the binding limit. Our Gmail sending limits guide has the full table.
Why did my Gmail API refresh token stop working?
The usual causes are an External app still in Testing status, where tokens expire after 7 days, a password change, which revokes tokens carrying Gmail scopes, a user revoking access, six months without use, or more than 100 tokens for one account on one OAuth client, which invalidates the oldest. In each case the refresh fails with invalid_grant and the person has to connect again.




