Gmail access

From terrylica/cc-skills · View interactive version

Gmail access is an AI agent skill from the GitHub repository terrylica/cc-skills. Access Gmail via CLI with 1Password OAuth: read, search and export email, and create drafts. Replies quote the sender verbatim as styled blockquotes and can carry file attachments, built and verified in one command. TRIGGERS - gmail, read email, search inbox, export emails, create draft, compose ema

How to use this skill

Skill file

Gmail Access

Read and search Gmail programmatically via Claude Code.

Self-Evolving Skill: This skill improves through use. If instructions are wrong, parameters drifted, or a workaround was needed β€” fix this file immediately, don't defer. Only update for real, reproducible issues.

MANDATORY PREFLIGHT (Execute Before Any Gmail Operation)

CRITICAL: You MUST complete this preflight checklist before running any Gmail commands. Do NOT skip steps.

Step 1: Check CLI Binary Exists

ls -la "$HOME/.claude/plugins/marketplaces/cc-skills/plugins/gmail-commander/scripts/gmail-cli/gmail" 2>/dev/null || echo "BINARY_NOT_FOUND"

If BINARY_NOT_FOUND: Build it first:

cd ~/.claude/plugins/marketplaces/cc-skills/plugins/gmail-commander/scripts/gmail-cli && bun run build

Step 2: Check GMAIL_OP_UUID Environment Variable

echo "GMAIL_OP_UUID: ${GMAIL_OP_UUID:-NOT_SET}"

If NOT_SET: You MUST run the Setup Flow below. Do NOT proceed to Gmail commands.

Step 2.5: Verify Account Context (CRITICAL)

ALWAYS verify you're accessing the correct email account for the current project.

# Show current project context
echo "=== Gmail Account Context ==="
echo "Working directory: $(pwd)"
echo "GMAIL_OP_UUID: ${GMAIL_OP_UUID}"

# Check where GMAIL_OP_UUID is defined (plain env: shell startup files, this shell, or inline)
echo ""
echo "=== GMAIL_OP_UUID Source ==="
grep -l "GMAIL_OP_UUID" ~/.zshenv ~/.zshrc 2>/dev/null || echo "Not in shell startup files (set in this shell or passed inline)"

# Quick connectivity test β€” shows the account email from a real email
echo ""
echo "=== Account Verification ==="
$GMAIL_CLI list -n 1 2>&1 | head -5

STOP and confirm with user before proceeding:

Multi-account disambiguation (when GMAIL_OP_UUID is NOT_SET but tokens exist). There is no whoami subcommand; map each cached token UUID to its mailbox by probing, then pick the one that fits the project:

πŸ”΄ Do NOT identify a mailbox from list -n 1 --json | jq '.[0].to'. That reads the recipient of the newest message, not the mailbox owner. When the newest item is an outgoing draft or a sent message, it reports the person you wrote TO. Measured 2026-08-18: the <token-uuid-prefix> token probed as an external correspondent's address while the mailbox is in fact you@example.com β€” a confident wrong answer in the one step whose entire job is to stop you acting on the wrong account.

Ask Gmail who it is instead. users/me/profile is authoritative:

# Which accounts are cached, which mailbox does each ACTUALLY own, and which alias is its DEFAULT?
bun "$HOME/.claude/plugins/marketplaces/cc-skills/plugins/gmail-commander/scripts/gmail-accounts.ts"
# one account, machine-readable:
bun "$HOME/.claude/plugins/marketplaces/cc-skills/plugins/gmail-commander/scripts/gmail-accounts.ts" --account <uuid> --json

It asks users/me/profile and settings/sendAs with each cached token and never prints a token. Do not read the token files yourself (jq .access_token, cat, python3): gmail-send-guard denies it, because they are bearer credentials for whole mailboxes. You need the send-as list before any --from: verificationStatus must be accepted, and if the alias marked DEFAULT is not the one you want, --from is mandatory, not optional. A message that reaches Gmail with no From line goes out under the DEFAULT alias.

A probe that returns invalid_grant means that account's refresh token is dead (see "Diagnosing invalid_grant"). Pick the working UUID whose mailbox matches the project and pass it inline as GMAIL_OP_UUID=<uuid> on each command. A child project often needs a DIFFERENT account than its parent β€” verify, never assume the parent's UUID.

Step 3: Verify Token Health

# Check cached token exists and is not expired
TOKEN_FILE="$HOME/.claude/tools/gmail-tokens/${GMAIL_OP_UUID}.json"
APP_CREDS="$HOME/.claude/tools/gmail-tokens/${GMAIL_OP_UUID}.app-credentials.json"
echo "Token file: $([ -f "$TOKEN_FILE" ] && echo "EXISTS" || echo "MISSING")"
echo "App credentials: $([ -f "$APP_CREDS" ] && echo "CACHED" || echo "MISSING β€” will need 1Password on first run")"

If token file is MISSING: First run will open a browser for OAuth consent. This is expected. If app credentials are MISSING: 1Password will be called once to cache client_id/client_secret, then never again.


Setup Flow (When GMAIL_OP_UUID is NOT_SET)

Follow these steps IN ORDER. Use AskUserQuestion at decision points.

Setup Step 1: Check 1Password CLI

command -v op && echo "OP_CLI_INSTALLED" || echo "OP_CLI_MISSING"

If OP_CLI_MISSING: Stop and inform user:

1Password CLI is required for this setup flow. Install with brew install 1password-cli on macOS, or from 1Password's package repository on Linux (where op needs OP_SERVICE_ACCOUNT_TOKEN, because there is no desktop app to sign it in). Without 1Password, supply the OAuth client through GMAIL_OAUTH_CLIENT_ID + GMAIL_OAUTH_CLIENT_SECRET or GMAIL_OAUTH_CLIENT_FILE instead: env-setup.md Β§ Without 1Password.

Setup Step 2: Discover Gmail OAuth Items in 1Password

# Try common vaults β€” "Claude Automation" for service accounts, "Employee" for interactive
for VAULT in "Claude Automation" "Employee" "Personal"; do
  ITEMS=$(op item list --vault "$VAULT" --format json 2>/dev/null | jq -r '.[] | select(.title | test("gmail|oauth|google"; "i")) | "\(.id)\t\(.title)"')
  [ -n "$ITEMS" ] && echo "=== Vault: $VAULT ===" && echo "$ITEMS"
done

Parse the output and proceed based on results:

Setup Step 3: User Selects OAuth Credentials

If items found, use AskUserQuestion with discovered items:

AskUserQuestion({
  questions: [{
    question: "Which 1Password item contains your Gmail OAuth credentials?",
    header: "Gmail OAuth",
    options: [
      // POPULATE FROM op item list RESULTS - example:
      { label: "Gmail API - project-f (56peh...)", description: "OAuth client in Employee vault" },
      { label: "Gmail API - personal (abc12...)", description: "Personal OAuth client" },
    ],
    multiSelect: false
  }]
})

If NO items found, use AskUserQuestion to guide setup:

AskUserQuestion({
  questions: [{
    question: "No Gmail OAuth credentials found in 1Password. How would you like to proceed?",
    header: "Setup",
    options: [
      { label: "Create new OAuth credentials (Recommended)", description: "I'll guide you through Google Cloud Console setup" },
      { label: "I have credentials elsewhere", description: "Help me add them to 1Password" },
      { label: "Skip for now", description: "I'll set this up later" }
    ],
    multiSelect: false
  }]
})

Setup Step 4: Confirm Where the UUID Goes

After user selects an item (with UUID), use AskUserQuestion:

AskUserQuestion({
  questions: [{
    question: "Where should GMAIL_OP_UUID be set?",
    header: "Configure",
    options: [
      { label: "This session only (Recommended)", description: "export GMAIL_OP_UUID in the current shell; nothing written to disk" },
      { label: "Per command", description: "Pass GMAIL_OP_UUID=<uuid> inline on every gmail call; safest when projects use different mailboxes" }
    ],
    multiSelect: false
  }]
})

If "This session only": run export GMAIL_OP_UUID=<selected-uuid>.

If "Per command": prefix each call, e.g. GMAIL_OP_UUID=<selected-uuid> $GMAIL_CLI list -n 1.

Never write it into an env file for a background bot or digest on this machine: those run in a private deployment with its own secret store, and the laptop launchd jobs they replaced were retired on 2026-09-24.

Setup Step 5: Verify

echo "GMAIL_OP_UUID: ${GMAIL_OP_UUID:-NOT_SET}"

Setup Step 6: Test Connection

GMAIL_OP_UUID="${GMAIL_OP_UUID}" $HOME/.claude/plugins/marketplaces/cc-skills/plugins/gmail-commander/scripts/gmail-cli/gmail list -n 1

If OAuth prompt appears: This is expected on first run. Browser will open for Google consent.


Gmail Commands (Only After Preflight Passes)

GMAIL_CLI="$HOME/.claude/plugins/marketplaces/cc-skills/plugins/gmail-commander/scripts/gmail-cli/gmail"

# List recent emails
$GMAIL_CLI list -n 10

# Search emails
$GMAIL_CLI search "from:someone@example.com" -n 20

# Search with date range
$GMAIL_CLI search "from:alice after:2026/01/27" -n 10

# Read specific email with full body
$GMAIL_CLI read <message_id>

# Read and download inline images (copy-pasted screenshots in compose)
$GMAIL_CLI read <message_id> --save-images

# Download inline images to a specific directory
$GMAIL_CLI read <message_id> --save-images --image-dir ./attachments/my-folder/

# Shorthand: --image-dir implies --save-images
$GMAIL_CLI read <message_id> --image-dir ./attachments/my-folder/

# JSON output with image metadata and saved paths
$GMAIL_CLI read <message_id> --save-images --json

# Download REAL file attachments (PDF, docx, csv, …) β€” distinct from inline images
$GMAIL_CLI read <message_id> --save-attachments

# Download attachments to a specific directory (implies --save-attachments)
$GMAIL_CLI read <message_id> --attachment-dir ./files/case-17402939/

# Export search results to JSON (full body + inlineImages + attachments metadata per message)
$GMAIL_CLI export -q "label:inbox" -o emails.json -n 100

# JSON output (for parsing)
$GMAIL_CLI list -n 10 --json

# Create a draft email
$GMAIL_CLI draft --to "user@example.com" --subject "Hello" --body "Message body"

# Create a draft reply (threads into existing conversation)
$GMAIL_CLI draft --to "user@example.com" --subject "Re: Hello" --body "Reply text" --reply-to <message_id>

# Draft with body loaded from a file (multi-paragraph bodies are awkward via --body)
$GMAIL_CLI draft --to "user@example.com" --subject "Report" --body-file ./email-body.txt

# Draft with file attachments (--attach is repeatable; MIME type guessed from extension)
$GMAIL_CLI draft --to "user@example.com" --subject "Q1 Report" \
  --body-file ./email-body.txt \
  --attach ./report.pdf \
  --attach ./screenshot.png

# Draft reply with both body-file and multiple attachments
$GMAIL_CLI draft --to "user@example.com" --subject "Re: Project" \
  --reply-to <message_id> \
  --body-file ./reply.txt \
  --attach ./diagram.pdf

# List drafts with their draft IDs
$GMAIL_CLI drafts -n 10

# Replace a draft in place (delete + recreate β€” the draft ID CHANGES)
$GMAIL_CLI draft-update <draft_id> --to "user@example.com" --from "me@example.com" \
  --subject "Same subject" --body-file ./revised-body.txt

`drafts --json` field names

The identifier field is draftId, not id. A .id selector silently yields null for every row rather than erroring, so a jq pipeline built on it looks like it worked and hands you nothing:

# WRONG β€” .id does not exist; prints "null" per draft and fails silently
$GMAIL_CLI drafts -n 10 --json | jq -r '.[] | "\(.id)\t\(.subject)"'

# RIGHT
$GMAIL_CLI drafts -n 10 --json | jq -r '.[] | "\(.draftId)\t\(.subject)"'

Full row shape: date, draftId, from, messageId, snippet, subject, threadId, to. Note the two distinct identifiers β€” draftId is what draft-update and draft-delete take; messageId is what read takes. Passing one where the other belongs fails or returns the wrong record.

draft-update returns a NEW draftId (it deletes and recreates). Any ID you noted earlier is dead the moment you update β€” re-list before a second update, and never cache a draft ID across edits.

Replying to someone: the house style (verbatim quotes, styled, one command)

Convention for every reply and every draft that quotes someone (the person being answered, an earlier message, a document): quote their words verbatim, each passage in its own > block, and put your answer underneath, outside the block. Never paraphrase inside a quotation, never correct their spelling, and never merge two of their passages into one. When a reply answers several points, alternate: one quoted passage, then the answer to it.

> the exact words being answered, copied as written

The answer to that passage.

The canonical builder (scripts/gmail-draft.ts) renders each > block as a <blockquote> in its own colour with a left bar (muted purple, italic; QUOTE_BLOCK_STYLE) in the HTML part, and keeps the > prefix in the plain-text part, so the reader sees at a glance whose words are whose. A block is a quotation only when every line in it starts with > (up to three spaces of indent); a stray > in prose stays prose. Do not hand-style quotes with HTML: the builder does it.

The command

bun "$HOME/.claude/plugins/marketplaces/cc-skills/plugins/gmail-commander/scripts/gmail-draft.ts" \
  --account <token-uuid> \
  --body ./reply.md \
  --from 'Jane Doe <alias@example.com>' \
  --reply-to <messageId> \
  --to 'Alex Roe <alex@example.com>' \
  --attach ./signed-agreement.pdf \
  --github-repo acme/handbook --github-reader jdoe \
  --google-authuser alex.roe@example.org \
  --replace <superseded draftId>

--attach is repeatable and optional; --to, --cc and --subject are inherited from --reply-to when omitted; --replace deletes the draft this one supersedes, only after the new one has passed verification. Before it prints its one JSON line the builder proves, against what Gmail actually stored: the Subject round-trips, the HTML part exists (byte-identical when --html is used) with no forced mid-sentence line breaks, every attachment's SHA-256 equals the file sent, and the thread holds exactly one draft (exit 1 naming the others when it does not; delete the superseded ones before sending). The output lists each attachment with its byte count and SHA-256.

GitHub issue links: numbered, linked, and only to people who can open them (since 2026-11-25)

Most issues we link to are in private repositories, and GitHub shows a plain 404 page, not "request access", to anyone without access. So, wherever rich text is allowed (every gmail-draft.ts draft without --html):

The JSON line carries githubAccess (repos β†’ {visibility, readers: {login: status}, notes}, privateRepos, accessOk) and accessNote (present, appended, suppressed or not-needed).

Google file links: open them in the reader's work account (since 2026-11-25)

House style: when a recipient reads mail in a personal Google account but opens the organisation's files in a work account, always pass --google-authuser <work address>. Without it, a Docs or Drive link opens in whichever account the browser picks, usually the personal one, and the reader requests access from the wrong account. Google's own web apps honour authuser=<email>, which opens the link in that signed-in account.

No earlier version may linger (every run, since 2026-11-21)

Every run reads the whole Drafts folder after the new draft is verified and compares it with what Gmail stored:

| Finding | Means | What happens |

| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- |

| superseded | Same sender, a shared recipient, the same subject once Braille Tally cells, Re:/Fwd:, case and spacing are ignored: an earlier version | Deleted with --prune-superseded; otherwise exit 3, each one named on stderr and in the JSON |

| related | Same sender and a shared recipient, a different subject | Listed on stderr and in the JSON (exit unchanged): you decide whether it is still in play |

Exit 4 means the draft is made but the folder could not be read; check it by hand. Why this exists: a new message (not a reply) starts its own thread, so the one-draft-per-thread check cannot see an earlier copy of it. On 2026-11-21 a batch of new emails was re-ranked and redrafted, and an outdated cover draft stayed next to its replacement until a manual sweep found it.

The rule, every time you draft: when a draft replaces one you know of, pass --replace <id>; when you redraft a batch, pass --prune-superseded; read every related line and delete what was merged, withdrawn or replaced. When a batch changes shape (items merged, withdrawn, re-ranked), sweep it against the list of drafts still in play:

bun "$HOME/.claude/plugins/marketplaces/cc-skills/plugins/gmail-commander/scripts/gmail-drafts-audit.ts" \
  --account <token-uuid> --keep-file ./manifest.json [--keep <draftId>,<draftId>] [--prune]

It flags every draft a newer one repeats and, with a keep list, every draft from the same sender to the same people that is not kept; drafts to anyone else are never touched. Without --prune it only reports (exit 3 when something lingers); with it, it deletes and then proves the drafts are gone (exit 0). --keep-file takes any file and keeps every draft id written in it, so a batch manifest works as it is. A draft the operator may have edited by hand is still a draft: if you are not sure an older version holds no edits of theirs, read it and compare before pruning.

Two things the converter will not do, and what to do instead:

The other path, and why replies do not use it

| Path | > quotes in the HTML part | File attachments | --cc | Read-back verification |

| ---------------------------------------- | ------------------------------------------------------------- | ----------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------- |

| scripts/gmail-draft.ts | Styled <blockquote> | --attach, repeatable (2026-10-30) | Yes | Built in (subject, HTML, forced breaks, attachment hashes, one draft per thread, no earlier version lingering) |

| gmail draft / draft-update (the CLI) | Unstyled: > is escaped and each line kept as plain text | --attach, repeatable | No | None; read it back yourself |

The CLI is fine for a quick plain note to yourself. Every reply that quotes someone goes through gmail-draft.ts. Do not attach a file through Gmail's web compose afterwards: on save Gmail regenerates the plain part from the HTML and the > marks are lost (measured 2026-10-30, before --attach existed).

After creating a draft, confirm it independently with read <messageId> --json --attachment-dir <dir>: every word equal to your source file, zero markdown markers, every > line present, and each downloaded attachment's hash equal to the original.

πŸ”΄ ATTRIBUTION DOCTRINE β€” run this before you ever write "they said X"

Reading an email and knowing who wrote which line are two different problems. The second one is harder, its answer is not in the text you get back by default, and when it goes wrong it does not throw β€” it produces a fluent, confident summary in which your own sentences are attributed to your correspondent, or half of what they wrote is silently missing. Every failure recorded in this section was of that shape: a wrong query returning an empty result, read as an empty world.

This applies by default. If a message is a reply β€” it has quoted history β€” and you intend to quote, summarise, attribute, decide, or act on what the sender said, you run the protocol below. It does not apply to listing, searching, triage, or counting.

The model: authorship βŠƒ colour βŠƒ marker

Three signals, nested, in descending order of trust. Using the wrong one as your primary is how both halves of the 2026-08-25 incident happened.

| Signal | Coverage | Where it lives | Trust |

| ----------------------------------------- | -------------------------------------------------------- | ------------------------------------ | ------------------------------------------------- |

| Quote depth | Complete β€” captures top matter AND inline insertions | text/plain: lines NOT prefixed > | Primary. But see the caveats β€” some clients lie |

| Colour | Proper subset β€” insertions inside a quoted region only | text/html ONLY | Disambiguates exactly where depth gets unreliable |

| Typed marker (>>>PT, @@@, [JS]) | Proper subset of colour β€” flags where a block STARTS | either part | Weakest. Never sufficient alone |

The protocol

bun scripts/attribution-parse.ts --id <messageId> --token-cmd '<cmd printing an access token>'

It prints which signals are actually present, what it attributes to the sender and why, and β€” the important part β€” what it cannot attribute. It reports CONFLICT when signals disagree and UNKNOWN when a line at quoted depth carries neither colour nor marker, because in that case the line genuinely could belong to either party. UNKNOWN is a correct answer. A tool that always decides is a tool that is sometimes confidently wrong.

πŸ”΄ It can also be confidently wrong when the quoted history carries no > at all. Measured 2026-10-30: a top-posted reply whose client put the earlier message under an On <date>, <name> wrote: line without > prefixes came back with every one of its 100 lines "Attributed to the sender" at quote depth 0, including the whole of OUR earlier letter quoted below that line, with no UNKNOWN and no CONFLICT. Before quoting or attributing, find the On … wrote: (or -----Original Message-----, From: … Sent: …) boundary yourself and treat everything below it as not the sender's, whatever the parser says. Open defect: the parser should detect that boundary.

Four rules that outlive any particular client

  1. Verify the convention per message. Never infer it from another message. The same correspondent used three different conventions in six days: css-coloured on 20 Aug, >>>PT markers with no colour at all on 21 Aug, legacy <font color> on 25 Aug. A message that _says_ "see my comments in blue" may contain no colour whatsoever β€” measured, twice.
  2. An empty result from a detector means your detector might be wrong. This is the single most expensive habit in this file. Zero colour spans, zero markers, zero matching rows β€” before concluding the sender did not do the thing, prove your query can find the thing when it is there. Same shape as the .[0].to mailbox probe and the .id draft field elsewhere in this skill.
  3. Read to the end of the paragraph. An audit of 22 authored segments found the residual misses were not caused by parsing at all β€” every one sat inside a segment already extracted, and was lost to first-sentence reading. Her structure is consistent and it is the opposite of a summary: the decision is in sentence one, the condition is in sentence two, and the condition is the part that binds you. "Let's go with that for now" _…and hope they increase it later_. "I am prepared to walk away" _…if we can find a local replacement and if we have time_.
  4. Prefer "I cannot tell" to a confident attribution. You will be forgiven for asking. You will not be forgiven for putting words in someone's mouth in a document they read.

Three measured exemplars, from one correspondent in six days

| Date | What she said her convention was | What the source actually contained | What broke |

| ------ | -------------------------------- | -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

| 20 Aug | "comments below in blue" | Exactly one css rgb(0,0,255) span; the rest marked >>>> / >>> | Colour was nearly useless; one comment was a truncated fragment (>>> should be) that needed a follow-up question to resolve |

| 21 Aug | "Pls see below with >>>PT" | No colour at all. Markers only | A colour-first parser would have found nothing and reported she wrote nothing |

| 25 Aug | "Pls see below in blue >>>PT" | 25 legacy <font color="#0000ff"> tags, zero css color:. 22 authored runs, 13 markers | A css-only detector returned zero and was read as "no colour used". Then the over-correction β€” "colour is the complete signal" β€” would have discarded her top matter, which is black and held the single most important decision in the message |

The lesson from the third row is the one to keep. Finding the bug is not the same as fixing the model. The first reading trusted markers and missed 9 of 22 segments; the corrected reading trusted colour and would have missed the migration date. Only the nested model survives both.

Red flags β€” stop and verify by hand

Before the archive, not after

Colour lives only in text/html. An archive that stores text/plain alone cannot answer "who said what" later β€” the evidence is simply not in it, and you will find yourself back at the API to answer a question your own records should have settled. Store both parts. read --json returns plain text only; fetch format=full for the html:

curl -s --noproxy '*' -H "Authorization: Bearer $TOK" \
  "https://gmail.googleapis.com/gmail/v1/users/me/messages/<id>?format=full" \
  | jq -r '[ .. | objects | select(.mimeType? == "text/html") | .body.data ]
           | map(select(. != null)) | .[0] // empty' \
  | tr '_-' '/+' | base64 -d > msg.html

And never strip quoted history when a sender replies inline β€” their answers live _inside_ the quotes, so stripping deletes the reply and keeps the signature.

The full catalogue

Normalisation that must precede every rule (quoted-printable, format=flowed, CRLF, colour canonicalisation, entity decoding, NFKC, Word conditional comments), per-client priors, typed-marker regexes, and the client artifacts that masquerade as authorship signals: references/attribution-parsing.md.

Inline Image Extraction

Emails often contain copy-pasted screenshots (inline images embedded in the HTML body, not file attachments). These appear as [image: image.png] placeholders in plain text but contain real image data accessible via the Gmail API.

Key Behavior

| Flag | Effect |

| -------------------- | ------------------------------------------------------------------------------------------ |

| --save-images | Download all inline images to disk (default: ~/.claude/tools/gmail-images/<message_id>/) |

| --image-dir <path> | Custom output directory (implies --save-images) |

| No flag | Shows image metadata (count, filenames, sizes) but does NOT download |

Output Sections (when images are present)

--- Inline Images (3) ---
  image.png   image/png   245.3 KB
  image.png   image/png   512.1 KB
  photo.jpg   image/jpeg  89.7 KB

--- Saved to Disk ---
  ./attachments/01_image.png  (251,234 B)
  ./attachments/02_image.png  (524,001 B)
  ./attachments/03_photo.jpg  (91,852 B)

--- Markdown References ---
![01_image.png](./attachments/01_image.png)
![02_image.png](./attachments/02_image.png)
![03_photo.jpg](./attachments/03_photo.jpg)

Important: Inline Images vs File Attachments

These are two disjoint channels, surfaced and downloaded separately:

| Channel | MIME parts | Metadata field | Download flag |

| -------------------- | ---------------------------------------------------------------------- | ---------------- | ----------------------------------------- |

| Inline images | image/* with attachmentId (copy-pasted screenshots) | inlineImages[] | --save-images / --image-dir |

| File attachments | non-image parts with a filename + attachmentId (PDF, docx, csv, …) | attachments[] | --save-attachments / --attachment-dir |

A plain gmail read <id> (no flags) shows both as metadata blocks (filename, MIME, size) without downloading β€” so you can see a PDF exists before pulling it. export and read --json both carry attachments[] (and inlineImages[]) in their JSON.

has:attachment matches real file attachments but NOT inline images. Gmail search has no operator for inline images. To discover emails with inline images, you must read the email and check the MIME tree.

Strategy for finding emails with inline images:

# Search by sender/date, then read each to check for images
$GMAIL_CLI search "from:sender@example.com after:2026/02/01" -n 10 --json | \
  jq -r '.[].id' | while read id; do
    COUNT=$($GMAIL_CLI read "$id" --json | jq '.inlineImages | length')
    [ "$COUNT" -gt 0 ] && echo "$id has $COUNT inline image(s)"
  done

Gmail Threading and Image Deduplication

When downloading images from a thread (multiple reply emails), later replies include all prior inline images. The last email in a thread is typically the superset.

Recommendation: For threaded conversations, download images from the latest reply only to avoid duplicates. Compare by file size if unsure.

Filename Collision Handling

Copy-pasted screenshots often all share the generic filename image.png. The CLI prefixes a zero-padded index: 01_image.png, 02_image.png, etc. These machine-generated names should be renamed to descriptive names for correspondence archival.

Post-Download: Annotation Transcription Protocol

When inline images contain handwritten annotations (circles, arrows, written text overlaid on screenshots), perform a systematic two-level analysis:

  1. Scene description: What does the screenshot show? (e.g., "Career portal main page showing position listings")
  2. Annotation inventory: Exhaustively catalog every non-original markup element:

Format annotations as blockquote captions beneath each image in markdown:

![Scene description β€” annotation summary](path/to/image.png)

> **Annotation transcription**: [Detailed description of visual markup.]
> Handwritten text reads: _"exact transcription here"_
> [Interpretation of what the annotator is requesting.]

Do NOT defer annotation transcription to a second pass. Capture all annotations on the first image examination to avoid redundant re-reads.

File Attachment Extraction

Real file attachments (PDF, docx, csv, …) are surfaced in attachments[] and downloaded with --save-attachments / --attachment-dir. Same fetch path as inline images, different metadata field.

# See what a message carries (no download) β€” both metadata blocks print
$GMAIL_CLI read <id>          # β†’ "--- Attachments (1) ---  foo.pdf  application/pdf  192.5 KB"

# Download to a chosen dir; files are index-prefixed + sanitized
$GMAIL_CLI read <id> --attachment-dir ./files/

# Discover which messages in a corpus actually carry attachments
$GMAIL_CLI search "from:sender@example.com has:attachment" -n 20 --json | \
  jq -r '.[].id' | while IFS= read -r id; do
    N=$($GMAIL_CLI read "$id" --json | jq '.attachments | length')
    [ "$N" -gt 0 ] && echo "$id β†’ $N attachment(s)"
  done

Why this matters for archival: in client/legal/operational mail the attached PDF (a protocol, a vendor form, a signed consent) is often the most important payload. A body-only export silently loses it. Always check attachments[] when archiving a correspondence thread.

Bulk Retrieval & Thread Archival

The canonical pattern for archiving a whole correspondence (verified on a 27-message, 15-thread client corpus):

  1. Scope with high-signal queries, not generic keywords. A bare keyword ("Acme") returns mostly newsletter noise. Prefer:
  1. Collect message IDs from search --json (snippet-only) and curate the in-scope set out of the noise.
  2. Fetch full bodies with a read --json loop (one file per message).
  3. Group by threadId client-side β€” Gmail's list/search APIs return individual messages, _not_ threads; you reconstruct threads yourself.
  4. Sort within a thread by parsed Date and strip quoted history (drop >-prefixed lines and everything after On … wrote:) to expose each message's new content.
  5. Pull attachments for any message whose attachments[] is non-empty.
# Robust batch fetch. NOTE: in zsh `for id in $VAR` does NOT word-split β€”
# always loop with `while IFS= read -r` over newline-delimited IDs.
printf '%s\n' $IDS | while IFS= read -r id; do
  [ -n "$id" ] && $GMAIL_CLI read "$id" --json > "raw/$id.json"
done

`export` is the one-call shortcut (fixed)

gmail export -q "<query>" -o out.json -n N writes one JSON array with full body + inlineImages[] + attachments[] per message β€” the batch-fetch shortcut when a single query captures your set. (Historical note: before the fix, export printed "Exported N emails to <path>" but wrote no file β€” outputPath was an unused parameter. If you see that symptom, the binary is stale; rebuild it.) export does not download attachment bytes β€” it only carries the metadata; use read --save-attachments per message for the files.

Creating Draft Emails

The draft command creates emails in your Gmail Drafts folder for review before sending.

Required options:

Optional:

MANDATORY Sender Alignment (NON-NEGOTIABLE)

The user has multiple Send As aliases configured in Gmail. The From address MUST match correctly or the recipient sees a reply from the wrong identity.

Rule 1 - Replies (--reply-to is set): pass --from ANYWAY.

The CLI attempts to auto-detect the sender by reading the original email's To/Cc/Delivered-To headers and matching against the user's Send As aliases, and prints what it chose:

From: you@example.com (auto-detected from original email)

Do not trust that line to be the identity you want. Auto-detection resolves to the _underlying account_ rather than the alias even when the original was addressed to the alias. Measured 2026-08-25: a message addressed to Jane Doe <alias@example.com> produced From: you@example.com, silently, with no warning β€” and alias@example.com is an accepted send-as alias on that very account. The draft looked successful.

This matters because the alias IS the identity, not a cosmetic label. Where a correspondence policy says which name to sign as, the account and the alias are different signatories, and getting it wrong sends the whole message as the wrong person. Note also that the _default_ alias on this account is you@company.example, which policy forbids for non-work mail β€” so an omitted or mis-detected --from can reach for an identity that is not merely wrong but prohibited.

So: always pass --from explicitly, on replies as well as new mail, and read the confirmation line back before trusting it. Pass it with the display name, --from "Jane Doe <alias@example.com>": a bare --from "alias@example.com" is stored as a bare From with no name (measured 2026-10-30, drafts --json showed the bare address), so the recipient's client may show only the address. The send-as display name is not filled in for you. If a draft was already created without it, draft-update <draftId> --from … recreates it correctly β€” it does not patch in place, so re-supply every other flag too.

There is no --cc flag. A reply draft therefore carries only To, even when the thread it replies into copied other people. Threading is preserved (In-Reply-To/References are set), but the copies are not. On a thread with a client and several vendors copied, this silently drops all of them from a reply sent on that client's behalf. Either restore the copies in the Gmail compose window before sending, or state plainly in your handoff that the CC list needs restoring β€” never let a draft go out assumed to be a reply-all.

Rule 2 - New emails (no --reply-to): When drafting a brand new email (not a reply), you MUST use AskUserQuestion to confirm which sender alias to use BEFORE creating the draft. Never assume the default.

AskUserQuestion({
  questions: [{
    question: "Which email address should this be sent from?",
    header: "Send As",
    options: [
      // Populate from known aliases or let user specify
      { label: "you@example.com", description: "Personal Gmail" },
      { label: "you@company.example", description: "Work email" },
    ],
    multiSelect: false
  }]
})

Then pass the selected address via --from:

$GMAIL_CLI draft --to "recipient@example.com" --from "you@example.com" --subject "Hello" --body "Message"

Rule 3 - Always verify in output: After draft creation, confirm the From address is shown in the output. If it's missing or wrong, delete the draft and recreate.

MANDATORY Post-Draft Step (NON-NEGOTIABLE)

After EVERY draft creation, you MUST present the user with a direct Gmail link to review the draft. This is critical because drafts should always be visually confirmed before sending.

Always output this after creating a draft:

Draft created! Review it here:
  https://mail.google.com/mail/u/0/#drafts
From: <sender_address>

Never skip this step. The user must be able to click through to Gmail and visually verify the draft content, sender, recipients, and threading before sending.

Example: Reply to an email (auto-detected sender)

# 1. Find the message to reply to
$GMAIL_CLI search "from:someone@example.com subject:meeting" -n 5 --json

# 2. Create draft reply - From is auto-detected from original email's To header
$GMAIL_CLI draft \
  --to "someone@example.com" \
  --subject "Re: Meeting tomorrow" \
  --body "Thanks for the update. I'll be there at 2pm." \
  --reply-to "19c1e6a97124aed8"

# 3. ALWAYS present the review link + From address to user

Example: New email (must ask user for sender)

# 1. Ask user which alias to send from (AskUserQuestion)
# 2. Create draft with explicit --from
$GMAIL_CLI draft \
  --to "someone@example.com" \
  --from "you@example.com" \
  --subject "Hello" \
  --body "Message body"

# 3. ALWAYS present the review link + From address to user

Note: After creating drafts, users need to re-authenticate if they previously only had read access. The CLI will prompt for OAuth consent to add the gmail.compose scope.

Gmail Search Syntax

| Query | Description |

| -------------------------- | ------------------------------------------------------------------------------------ |

| from:sender@example.com | From specific sender |

| to:recipient@example.com | To specific recipient |

| subject:keyword | Subject contains keyword |

| after:2026/01/01 | After date |

| before:2026/02/01 | Before date |

| label:inbox | Has label |

| is:unread | Unread emails |

| has:attachment | Has file attachment (does NOT match inline images β€” see Inline Image Extraction) |

Reference: <https://support.google.com/mail/answer/7190>

Environment Variables

| Variable | Required | Description |

| ---------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

| GMAIL_OP_UUID | Yes | 1Password item UUID for OAuth credentials |

| GMAIL_OP_VAULT | No | 1Password vault (default: Employee) |

| HTTPS_PROXY | No | Honored by the underlying gaxios library, BUT the CLI auto-injects *.googleapis.com into NO_PROXY at startup so corporate proxies don't break Gmail traffic. See "Proxy Auto-Bypass" below. |

Proxy Auto-Bypass for Google API Hosts

If HTTPS_PROXY (or HTTP_PROXY) is set in the environment, the CLI automatically injects the following hosts into NO_PROXY at module load β€” before any auth or API call is made:

Why this exists: many corporate networks (Cloudflare WARP, mitmproxy local interceptors, ITP-style local proxies) can't tunnel CONNECT to Google API hosts. When the proxy fails, the response surface returns HTTP 502 with an empty error body β€” the googleapis library throws a gaxios error whose .message is empty, which used to render as a useless empty Error: in stderr.

By force-bypassing the proxy for Google hosts, end-users with a corporate proxy can run the CLI without manually setting NO_PROXY or unsetting HTTPS_PROXY per-command.

Idempotent: the injection only adds entries that aren't already present in NO_PROXY. If you've manually configured NO_PROXY=.googleapis.com, the CLI leaves it alone.

Diagnosing remaining proxy issues (rare): if you still see HTTP 5xx errors, the CLI's new error formatter prints the full URL + response body + a hint. Check that HTTPS_PROXY was set BEFORE the CLI started (env-var detection is one-shot at module load).

Error Messages

The CLI's top-level error handler renders unknown errors as structured messages with HTTP status, request URL, response body snippet, and a category-specific hint. Example for a 404 on a bogus draft ID:

Error: HTTP 404 Not Found DELETE https://gmail.googleapis.com/gmail/v1/users/me/drafts/r-doesnotexist123
  body: {"error":{"code":404,"message":"Requested entity was not found.",...}}
  hint: message / draft ID not found. List existing drafts with `gmail drafts` first.

Hint categories:

| Status | Hint |

| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |

| 401 | Token expired/revoked. Delete ~/.claude/tools/gmail-tokens/$GMAIL_OP_UUID.json to force re-auth. |

| 403 | OAuth scope insufficient (drafts/attachments need gmail.compose) or Send As alias not configured. |

| 404 | Message / draft ID not found. List existing drafts with gmail drafts first. |

| 413 | Attachment(s) exceed Gmail's 25 MB per-message limit. Split or use Drive links. |

| 502/503/504 | Gateway error β€” usually a proxy that can't tunnel to Google. The auto-bypass should prevent this; check that HTTPS_PROXY was set BEFORE the CLI started. |

Network-layer errors (ECONNREFUSED, ENOTFOUND, etc.) are surfaced with their error code instead of the empty Error: of the prior implementation.

Token Architecture

Storage Layout

~/.claude/tools/gmail-tokens/
β”œβ”€β”€ <uuid>.json                    # OAuth token (access + refresh), refreshed hourly
└── <uuid>.app-credentials.json    # client_id + client_secret (static, cached from 1Password)

Auth Flow (1Password is one-time only)

  1. First run: 1Password is called to fetch client_id/client_secret β†’ cached to <uuid>.app-credentials.json
  2. First run: Browser opens for Google OAuth consent β†’ tokens saved to <uuid>.json
  3. All subsequent runs: Reads cached files only β€” no 1Password call, no browser
  4. Hourly refresher (launchd): Keeps access_token alive by calling Google's token endpoint with the cached refresh_token

To force a fresh 1Password lookup (e.g., after rotating OAuth app credentials):

rm ~/.claude/tools/gmail-tokens/<uuid>.app-credentials.json

Diagnosing `invalid_grant`

A refresh token in a Google OAuth app whose publishing status is "Testing" expires after 7 days β€” period. The hourly refresher renews the _access_ token but does NOT extend the _refresh_ token's 7-day clock, so a Testing-mode account dies roughly weekly and can only be revived by a browser re-consent. (An app in "In production" status issues long-lived refresh tokens that don't expire on that clock.)

Recovery (re-consent): Delete the expired token file and re-authorize via browser:

# 1. Back up and remove the expired token
mv ~/.claude/tools/gmail-tokens/<uuid>.json ~/.claude/tools/gmail-tokens/<uuid>.json.expired

# 2. Run any gmail command β€” browser will open for OAuth consent
#    (sign in with the SPECIFIC account that <uuid> maps to β€” see accounts.json labels)
$GMAIL_CLI list -n 1

# 3. Verify the hourly refresher picks up the new token
~/.claude/automation/gmail-token-refresher/gmail-oauth-token-refresher 2>&1

# 4. Clean up backup
rm ~/.claude/tools/gmail-tokens/<uuid>.json.expired

Durable fix (stop the weekly death β€” "keep everything re-auth"): publish the OAuth app to Production so refresh tokens stop expiring on the 7-day clock.

  1. If an account survives indefinitely while another dies weekly, they use different OAuth apps (check accounts.json vault per uuid). Only the dying one is stuck in Testing.
  2. Google Cloud Console β†’ the project owning that OAuth client (the client_id prefix is the project number; the CLI prints the full client_id in the consent URL during re-auth).
  3. APIs & Services β†’ OAuth consent screen β†’ Publishing status β†’ Publish app β†’ confirm "In production". (External + Production with Gmail scopes may warn "unverified" for _new_ users, but already-consented accounts get long-lived refresh tokens; full Google verification is only needed for public/>100-user apps.)
  4. Re-consent once more after publishing; the hourly refresher then keeps the access token fresh indefinitely with no weekly re-auth.

Multi-Account Token Status

# Check all accounts at once: mailbox, access-token expiry, scopes, send-as aliases
bun "$HOME/.claude/plugins/marketplaces/cc-skills/plugins/gmail-commander/scripts/gmail-accounts.ts"

References

Post-Change Checklist

Evolution Log

Post-Execution Reflection

After this skill completes, reflect before closing the task:

  1. Locate yourself. β€” Find this SKILL.md's canonical path before editing.
  2. What failed? β€” Fix the instruction that caused it.
  3. What worked better than expected? β€” Promote to recommended practice.
  4. What drifted? β€” Fix any script, reference, or dependency that no longer matches reality.
  5. Log it. β€” Evolution-log entry with trigger, fix, and evidence.

Do NOT defer. The next invocation inherits whatever you leave behind.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.