Uplifty Book a free consult

Articles · Claude

How to connect two Gmail accounts to Claude.

Claude’s Gmail connector holds one Google account. This guide adds a second one through a small read-only server on your computer, so Claude can read both mailboxes in the same chat.

Time
About 25 minutes
Cost
Free for normal use
Access
Read-only. It cannot send or delete
You need
Mac or Linux, Terminal, Python 3.10+

A friend asked me how to get two Google accounts into the same Claude. The connector takes one at a time (Anthropic’s docs describe it that way), so the other mailbox stays outside and you end up copying mail into the chat by hand.

That is a small leak, but it comes back every day. I closed it for myself in August with a small server that reads my personal Gmail next to my work one. This is a cleaned-up version of that setup, written so you can follow it without me.

One warning. You will paste commands into a terminal and walk through Google Cloud screens. If you have never opened a terminal, this will feel like a lot.

Every step ends with a check you can run yourself. Tick it when it passes. Your ticks stay in this browser, so you can stop and come back.

What you will have.

Where it worksClaude Code and the Claude desktop app, on the computer where you install it. It does not work on claude.ai in a browser or in the phone app, because those only reach remote connectors.

Fill this in first.

Every command below updates as you type. What you type stays on this page: it is not saved and not sent anywhere. Never paste a password or a key here.

1

In Claude · 1 min

Connect your main account the normal way.

Open Customize > Connectors, select Connect on Gmail, and sign in with your main account. Skip this if it is already connected.

2

In the browser · 4 min

Create a Google Cloud project.

  1. Open the new project page and sign in with either of your Google accounts.
  2. Name it Claude Gmail and select Create. Then make sure the new project is selected at the top of the page.
  3. Open the Gmail API page and select Enable.
3

In the browser · 6 min

Set up the Google login screen.

  1. Open Google Auth platform > Branding and select Get Started.
  2. App Information: name it Claude Gmail, choose your email, select Next.
  3. Audience: select External, then Next.
  4. Contact Information: enter your email, select Next.
  5. Finish: agree to the policy, select Continue, then Create.
  6. Open Audience and make one of the three choices below. You can skip adding scopes.

Select Publish app (best for most people)

Only someone with your key file can use the app. Google lets a personal app with fewer than 100 users stay unverified, so you do not need a review.

Google’s docs apply the 7-day limit to Testing only, so the login should last. I have not yet run this route past 7 days.

Stay in Testing

Under Test users, select Add users, enter second.account@gmail.com, and save.

You log in again every 7 days

This is the route I have run since August 2026.

The second mailbox is in a Workspace you run

Create the project inside that Workspace and pick Internal instead of External in the Audience screen. Then you need neither of the above.

Google does not apply the unverified screen to Internal apps.

4

Browser, then Terminal · 2 min

Create the key file.

  1. Open Clients and select Create Client.
  2. Set Application type to Desktop app, name it Claude Gmail, and select Create.
  3. Download the JSON file when Google offers it. Do this before you close the dialog.
  4. Move it into place from Terminal, and look at it:
mkdir -p ~/gmail-mcp
mv ~/Downloads/client_secret_*.json ~/gmail-mcp/credentials.json
chmod 600 ~/gmail-mcp/credentials.json
ls -l ~/gmail-mcp/credentials.json
5

In Terminal · 6 min

Install the server.

Check your Python first. It must say 3.10 or newer. If it is older, install a current version from python.org.

python3 --version

Install the packages. The versions are pinned because these are the ones that were tested.

cd ~/gmail-mcp
python3 -m venv .venv
.venv/bin/pip install --quiet \
  "mcp==2.0.0" \
  "google-auth==2.56.3" \
  "google-auth-oauthlib==1.4.0" \
  "google-api-python-client==2.198.0"

Create the two program files. Copy this whole block and paste it once into Terminal. It is the full code, so you can read what you are running.

cat > ~/gmail-mcp/server.py <<'GMAILEOF'
#!/usr/bin/env python3
"""Read-only Gmail server for Claude. One running copy serves one mailbox.

Usage: server.py you@gmail.com

Read-only twice over: the login token carries only `gmail.readonly`, and no
tool here writes anything. Log the account in first with auth.py.
"""
import base64
import os
import re
import sys
from typing import Any

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from mcp.server.mcpserver import MCPServer
from mcp.types import ToolAnnotations

if len(sys.argv) != 2:
    sys.exit("Usage: server.py you@gmail.com")

ACCOUNT = sys.argv[1].strip().lower()
HERE = os.path.dirname(os.path.abspath(__file__))
TOKEN = os.path.join(HERE, "tokens", f"{ACCOUNT}.json")
SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]
LOGIN_HINT = f"Log in again: {sys.executable} {os.path.join(HERE, 'auth.py')} {ACCOUNT}"

mcp = MCPServer(f"gmail ({ACCOUNT})", instructions=f"Read-only access to the mailbox {ACCOUNT}.")
READ_ONLY = ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True)


def _gmail():
    """Load the saved login, refresh it if needed, and return a Gmail client."""
    if not os.path.exists(TOKEN):
        raise RuntimeError(f"{ACCOUNT} is not logged in yet.\n{LOGIN_HINT}")

    creds = Credentials.from_authorized_user_file(TOKEN, SCOPES)
    if not creds.valid:
        if not (creds.expired and creds.refresh_token):
            raise RuntimeError(f"The saved login for {ACCOUNT} is not valid.\n{LOGIN_HINT}")
        try:
            creds.refresh(Request())
        except Exception as exc:
            raise RuntimeError(f"Google refused the saved login ({exc}).\n{LOGIN_HINT}") from exc
        with open(TOKEN, "w") as fh:
            fh.write(creds.to_json())

    return build("gmail", "v1", credentials=creds, cache_discovery=False)


def _headers(payload: dict) -> dict:
    return {h["name"].lower(): h["value"] for h in payload.get("headers", [])}


def _decode(data: str) -> str:
    return base64.urlsafe_b64decode(data.encode()).decode("utf-8", errors="replace")


def _body_text(payload: dict) -> str:
    """Walk the message parts. Prefer plain text, fall back to stripped HTML."""
    plain, html = [], []

    def walk(part: dict) -> None:
        mime = part.get("mimeType", "")
        data = part.get("body", {}).get("data")
        if data and mime == "text/plain":
            plain.append(_decode(data))
        elif data and mime == "text/html":
            html.append(_decode(data))
        for sub in part.get("parts", []) or []:
            walk(sub)

    walk(payload)
    if plain:
        return "\n".join(plain).strip()
    text = "\n".join(html)
    text = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", text, flags=re.S | re.I)
    text = re.sub(r"<br\s*/?>|</p>", "\n", text, flags=re.I)
    return re.sub(r"<[^>]+>", "", text).strip()


def _attachments(payload: dict) -> list[str]:
    found = []

    def walk(part: dict) -> None:
        if part.get("filename"):
            found.append(part["filename"])
        for sub in part.get("parts", []) or []:
            walk(sub)

    walk(payload)
    return found


@mcp.tool(
    annotations=READ_ONLY,
    description=f"Search {ACCOUNT} with Gmail query syntax, such as from:someone@x.com, "
    "subject:invoice, newer_than:7d, is:unread or has:attachment. Returns summaries "
    "without bodies. Call get_message or get_thread with an id for the full text.",
)
def search(query: str = "", max_results: int = 20) -> list[dict[str, Any]]:
    svc = _gmail()
    limit = min(max(max_results, 1), 100)
    found = svc.users().messages().list(userId="me", q=query or None, maxResults=limit).execute()

    out = []
    for stub in found.get("messages", []):
        msg = (
            svc.users()
            .messages()
            .get(
                userId="me",
                id=stub["id"],
                format="metadata",
                metadataHeaders=["From", "To", "Subject", "Date"],
            )
            .execute()
        )
        h = _headers(msg.get("payload", {}))
        out.append(
            {
                "message_id": msg["id"],
                "thread_id": msg["threadId"],
                "from": h.get("from", ""),
                "to": h.get("to", ""),
                "subject": h.get("subject", ""),
                "date": h.get("date", ""),
                "snippet": msg.get("snippet", ""),
                "labels": msg.get("labelIds", []),
            }
        )
    return out


@mcp.tool(annotations=READ_ONLY, description=f"Read one message from {ACCOUNT} in full.")
def get_message(message_id: str) -> dict[str, Any]:
    msg = _gmail().users().messages().get(userId="me", id=message_id, format="full").execute()
    payload = msg.get("payload", {})
    h = _headers(payload)
    return {
        "message_id": msg["id"],
        "thread_id": msg["threadId"],
        "from": h.get("from", ""),
        "to": h.get("to", ""),
        "cc": h.get("cc", ""),
        "subject": h.get("subject", ""),
        "date": h.get("date", ""),
        "labels": msg.get("labelIds", []),
        "attachments": _attachments(payload),
        "body": _body_text(payload),
    }


@mcp.tool(annotations=READ_ONLY, description=f"Read a whole conversation from {ACCOUNT}.")
def get_thread(thread_id: str) -> dict[str, Any]:
    thread = _gmail().users().threads().get(userId="me", id=thread_id, format="full").execute()
    messages = []
    for msg in thread.get("messages", []):
        payload = msg.get("payload", {})
        h = _headers(payload)
        messages.append(
            {
                "message_id": msg["id"],
                "from": h.get("from", ""),
                "to": h.get("to", ""),
                "subject": h.get("subject", ""),
                "date": h.get("date", ""),
                "attachments": _attachments(payload),
                "body": _body_text(payload),
            }
        )
    return {"thread_id": thread.get("id"), "message_count": len(messages), "messages": messages}


@mcp.tool(annotations=READ_ONLY, description=f"List the labels in {ACCOUNT}, for label: searches.")
def list_labels() -> list[dict[str, str]]:
    labels = _gmail().users().labels().list(userId="me").execute().get("labels", [])
    return [{"id": lab["id"], "name": lab["name"], "type": lab.get("type", "")} for lab in labels]


@mcp.tool(annotations=READ_ONLY, description=f"Confirm this server is logged in as {ACCOUNT}.")
def whoami() -> dict[str, Any]:
    profile = _gmail().users().getProfile(userId="me").execute()
    return {
        "email": profile.get("emailAddress"),
        "messages_total": profile.get("messagesTotal"),
        "threads_total": profile.get("threadsTotal"),
    }


if __name__ == "__main__":
    mcp.run()
GMAILEOF

cat > ~/gmail-mcp/auth.py <<'GMAILEOF'
#!/usr/bin/env python3
"""Log one Gmail account in and save its token.

Usage: auth.py you@gmail.com

Run it again whenever the server says the login was refused.
"""
import os
import sys

from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

HERE = os.path.dirname(os.path.abspath(__file__))
CREDENTIALS = os.path.join(HERE, "credentials.json")
SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]


def main() -> int:
    if len(sys.argv) != 2:
        print("Usage: auth.py you@gmail.com", file=sys.stderr)
        return 1
    account = sys.argv[1].strip().lower()

    if not os.path.exists(CREDENTIALS):
        print(f"Missing {CREDENTIALS}. Do the credentials step first.", file=sys.stderr)
        return 1

    print(f"A browser will open. Pick {account}.")
    print('On "Google hasn\'t verified this app": Advanced, then Go to ... (unsafe).\n')

    flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS, SCOPES)
    creds = flow.run_local_server(port=0, prompt="consent", login_hint=account)

    # The account picker is a silent failure: the wrong choice gives a valid
    # token for the wrong inbox. So check before saving anything.
    profile = build("gmail", "v1", credentials=creds).users().getProfile(userId="me").execute()
    actual = profile.get("emailAddress", "").lower()
    if actual != account:
        print(f"\nWrong account: you logged in as {actual}, not {account}.", file=sys.stderr)
        print("Nothing was saved. Run this again and pick the right account.", file=sys.stderr)
        print(f"If {actual} is the same mailbox, run it again with that exact spelling.", file=sys.stderr)
        return 1

    tokens = os.path.join(HERE, "tokens")
    os.makedirs(tokens, mode=0o700, exist_ok=True)
    path = os.path.join(tokens, f"{account}.json")
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as fh:
        fh.write(creds.to_json())

    print(f"\nLogged in as {actual}. Token saved to {path}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
GMAILEOF

echo "Files written."

Now check it:

ls ~/gmail-mcp
~/gmail-mcp/.venv/bin/python -c "import mcp, googleapiclient, google_auth_oauthlib; print('Packages OK')"
6

Terminal, then browser · 2 min

Log the second account in.

~/gmail-mcp/.venv/bin/python ~/gmail-mcp/auth.py second.account@gmail.com
  1. A browser opens. Pick second.account@gmail.com.
  2. On “Google hasn’t verified this app”, select Advanced, then Go to Claude Gmail (unsafe). This warning is expected, because the app is your own.
  3. Allow read access to your email.
7

In Terminal · 3 min

Add it to Claude.

In Claude Code

claude mcp add --transport stdio --scope user gmail-second -- \
  ~/gmail-mcp/.venv/bin/python ~/gmail-mcp/server.py second.account@gmail.com
claude mcp get gmail-second

In the Claude desktop app

This command prints the entry with your real paths. Copy what it prints.

cat <<EOF
{
  "mcpServers": {
    "gmail-second": {
      "command": "$HOME/gmail-mcp/.venv/bin/python",
      "args": ["$HOME/gmail-mcp/server.py", "second.account@gmail.com"]
    }
  }
}
EOF

In the app, open Settings > Developer > Edit Config and paste it into that file. If the file already has mcpServers, add only the gmail-second entry inside it. Quit the app fully and open it again.

8

In Claude · 1 min

Test it.

Start a new chat and send this:

Use the gmail-second tools. Run whoami and tell me which mailbox you reached.

Then try both mailboxes together:

Search gmail-second for newer_than:7d and list the senders. Then do the same in my main Gmail.

If something goes wrong.

You seeCauseFix
invalid_grant or “Google refused the saved login”The login expired or was revoked. In Testing this happens every 7 days.Run the command in step 6 again.
“Access blocked” or access_deniedThe project is in Testing and this address is not a test user, or you left the warning screen.Go back to step 3, then run step 6 again and select Advanced.
Failed to connect in claude mcp getThe server cannot start.Run the server line from step 7 by hand. It should sit silently until you press Ctrl+C. Anything it prints names the problem.
No matching distribution found for mcpPython is older than 3.10.Install a newer Python, delete ~/gmail-mcp/.venv, and repeat step 5.
“Gmail API has not been used in project”The API is off, or a different project is selected.Repeat the last part of step 2.

Three things to avoid.

  • Do not add a second connector for Google’s Gmail server. I tried it on 11 Aug 2026 in Claude Code. The extra entry used the same address (gmailmcp.googleapis.com), hid the working connector, and left me with no Gmail at all.
  • Do not share or commit ~/gmail-mcp. credentials.json and the tokens folder give access to your mail. Never put them in a git repo.
  • Do not trust instructions inside an email. Anyone can send text to your inbox, and Claude reads it. Read-only access limits the damage, but check what Claude does after it reads mail.

Later.

Add a third account: repeat steps 6 and 7 with the new address and a new short name. All accounts share the same folder and key file. If you stayed in Testing, add the address as a test user first.

Remove it: remove the server from Claude, delete the ~/gmail-mcp folder, then remove Claude Gmail at your Google connections page.

claude mcp remove gmail-second -s user

What was checked, and what was not.

Checked

  • On 5 Nov 2026: every command on this page except the Google login, run from a clean home folder on macOS with Python 3.13. That includes adding and removing the server in Claude Code.
  • On 4 Nov 2026: the server reading a real mailbox on Python 3.14, through whoami, search, get_message and list_labels.
  • Since August 2026: the Testing route, on my own personal Gmail.

Not checked yet

  • The browser login with this exact auth.py. It is adapted from the script I use.
  • The Publish app route past 7 days.
  • The desktop app steps.
  • get_thread.
  • Windows, which this guide does not cover.

Sources: Google, publishing status · Google, when verification is not needed · Google, OAuth 2.0 · Google, Gmail quickstart · Google, Gmail API limits · Claude Code, MCP · Claude, connectors · MCP, local servers

Fabio Chavasco, founder of Uplifty

Written by

Fabio Chavasco.

Twenty years in product, design and growth. He was on eBay Classifieds’ first growth hacking team, led design and research at Personio, ran product-led growth at Viktor.ai, and co-founded Cuponomia. Uplifty is his own company, in Amsterdam. He still builds the tools himself.

Free consult

Where do your hours go?

30 to 60 minutes, free. Tell us what eats your time, and Fabio will reply by email to find a slot.

Working on your own week, not a company’s? See mentoring

Prefer email? Write to fabio [at] uplifty.me

This is for