gmail-access — скилл для Claude Code: что делает и как установить
Скилл gmail-access для Claude Code подключает Gmail через CLI: читает и ищет письма, выгружает результаты и создаёт черновики. Даёт доступ к переписке в ходе работы над проектом.
MIT 137 установок ★ 3 обновлён 2026-10-25
npx skills add terrylica/cc-skills --skill gmail-access -a claude-codeЧто делает gmail-access
Скилл подключает к агенту консольный клиент Gmail: чтение писем, поиск по ящику, выгрузка найденного и создание черновиков без отправки. Авторизация идёт через OAuth-клиент, который лежит в 1Password, а полученный токен кэшируется в ~/.claude/tools/gmail-tokens/.
Перед любой операцией скилл прогоняет предполётную проверку: собран ли бинарник gmail, задана ли переменная GMAIL_OP_UUID, жив ли кэш токена. Бинарник собирается через bun install --frozen-lockfile && bun run build в каталоге scripts/gmail-cli. Без GMAIL_OP_UUID работа не начнётся: скилл уйдёт в мастер настройки и станет искать OAuth-элементы по хранилищам 1Password.
Несколько ящиков различаются по UUID, а не по рабочему каталогу, поэтому дочернему проекту может понадобиться не тот аккаунт, что родительскому. Владельца ящика скилл советует выяснять через users/me/profile, а не по получателю в самом свежем письме: там часто стоит адресат, которому вы писали. Файлы токенов читать напрямую не выйдет, gmail-send-guard это блокирует, потому что внутри лежит доступ ко всему ящику.
Какие задачи решает
- выгрузить переписку с подрядчиком в файл
- найти в ящике письма по отправителю и дате
- собрать черновик ответа, не отправляя его
- проверить, к какому ящику привязан текущий проект
- подтянуть последнее письмо, чтобы понять контекст задачи
Примеры запросов агенту
- Покажи, какой ящик Gmail подключён сейчас, и выведи последнее письмо.
- Найди в Gmail письма от биллинга и сохрани их в
inbox-export.md. - Создай черновик письма с итогами недели, отправлять не надо.
Как установить gmail-access
1Через Skills CLI (Vercel)
npx skills add terrylica/cc-skills --skill gmail-access -a claude-code2Вручную: положить файлы
~/.claude/skills/gmail-access/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/gmail-access/
1Через Skills CLI (Vercel)
npx skills add terrylica/cc-skills --skill gmail-access -a codex2Вручную: положить файлы
.agents/skills/gmail-access/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add terrylica/cc-skills --skill gmail-access -a cursor2Вручную: положить файлы
.cursor/skills/gmail-access/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install terrylica/cc-skills plugins/gmail-commander/skills/gmail-access2Вручную: положить файлы
.github/skills/gmail-access/SKILL.md1Через Skills CLI (Vercel)
npx skills add terrylica/cc-skills --skill gmail-access -a gemini-cli2Командой платформы
gemini skills install https://github.com/terrylica/cc-skills --path plugins/gmail-commander/skills/gmail-accessВручную: положить файлы
.devin/skills/gmail-access/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add terrylica/cc-skills --skill gmail-access -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о gmail-access
Как установить gmail-access в Claude Code?
Выполните npx skills add terrylica/cc-skills --skill gmail-access -a claude-code. Файл скилла появится по пути ~/.claude/skills/gmail-access/SKILL.md.
Что делает gmail-access?
Даёт агенту доступ к Gmail из командной строки: чтение, поиск, выгрузка писем и создание черновиков. Авторизация идёт через OAuth-клиент, сохранённый в 1Password.
Что нужно подготовить до первого запуска?
1Password CLI ставится через brew install 1password-cli, переменная GMAIL_OP_UUID должна быть задана, а бинарник gmail собран заранее. При первом обращении откроется браузер для согласия OAuth.
Исходный текст
SKILL.md · MIT
---
name: gmail-access
description: "Access Gmail via CLI with 1Password OAuth: read, search and export email, and create drafts. TRIGGERS - gmail, read email, search inbox, export emails, create draft, compose email."
allowed-tools: Read, Bash, Grep, Glob, Write, AskUserQuestion
---
# 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
```bash
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:
```bash
cd ~/.claude/plugins/marketplaces/cc-skills/plugins/gmail-commander/scripts/gmail-cli && bun install --frozen-lockfile && bun run build
```
### Step 2: Check GMAIL_OP_UUID Environment Variable
```bash
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.**
```bash
# 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:
- The `list -n 1` output shows the account's inbox — verify this matches the project's intended email
- If the wrong account is shown, re-run with the right UUID passed inline (`GMAIL_OP_UUID=<uuid> $GMAIL_CLI ...`); nothing selects the account from the working directory
- If mismatch, inform user and do NOT proceed
**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 `[email protected]` — 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:
```bash
# 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
```bash
# 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
```bash
command -v op && echo "OP_CLI_INSTALLED" || echo "OP_CLI_MISSING"
```
**If OP_CLI_MISSING**: Stop and inform user:
> 1Password CLI is required. Install with: `brew install 1password-cli`
### Setup Step 2: Discover Gmail OAuth Items in 1Password
```bash
# 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
}]
})
```
- If "Create new OAuth credentials": Read and present [references/gmail-api-setup.md](./references/gmail-api-setup.md)
- If "I have credentials elsewhere": Guide user to add to 1Password with required fields
- If "Skip for now": Inform user the skill won't work until configured
### 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
```bash
echo "GMAIL_OP_UUID: ${GMAIL_OP_UUID:-NOT_SET}"
```
### Setup Step 6: Test Connection
```bash
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)
```bash
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:[email protected]" -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 "[email protected]" --subject "Hello" --body "Message body"
# Create a draft reply (threads into existing conversation)
$GMAIL_CLI draft --to "[email protected]" --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 "[email protected]" --subject "Report" --body-file ./email-body.txt
# Draft with file attachments (--attach is repeatable; MIME type guessed from extension)
$GMAIL_CLI draft --to "[email protected]" --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 "[email protected]" --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 "[email protected]" --from "[email protected]" \
--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:
```bash
# 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.
## Quoting someone in a draft: verbatim, and in its own colour
**Convention for every draft:** whenever a draft quotes someone (the person being answered, an earlier message, a document), quote their words **verbatim**, each passage in its own `> ` block, and put your reply outside the block. Never paraphrase inside a quotation, never correct their spelling, and never merge two of their passages into one. Use this whenever a reply answers several points: one quoted passage, then the answer to it.
```markdown
> the exact words being answered, copied as written
The answer to that passage.
```
The canonical builder (`scripts/gmail-draft.ts`, which every draft goes through) renders each `> ` block as a `<blockquote>` in its own colour with a left bar 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.
## 🔴 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
```bash
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.
### 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
- The sender describes a convention that your parser cannot find (says "in blue", no colour detected).
- Coloured-run count and marker count differ — the difference is unmarked continuation text, and continuations are where the conditions live.
- Colour appears in `text/html` but the matching text is absent from `text/plain`, or vice versa. **Parse both parts and take the union; never prefer one.** Clients generate them independently, so offsets from one do not map onto the other.
- More than two apparent authors in a two-party thread — usually one author split across colour spellings (`blue` / `#00F` / `rgb(0,0,255)`), which is why colour must be normalised to a canonical triple before any equality test.
- Any CJK full-width punctuation (`>>`, `:`, `【PT】`). `^>` does not match `>`, so a full-width-quoted thread parses as 100% new text by the last replier.
### 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:
```bash
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](./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 ---



```
### 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:**
```bash
# Search by sender/date, then read each to check for images
$GMAIL_CLI search "from:[email protected] 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:
- **Hand-drawn shapes**: circles, ovals, arrows, underlines, crosses — note what they encompass
- **Handwritten text**: transcribe verbatim in quotes, note legibility and location on the image
- **Typed test inputs**: text entered into form fields visible in the screenshot
- **Highlights or color markings**: note color and what is highlighted
**Format annotations as blockquote captions** beneath each image in markdown:
```markdown

> **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.
```bash
# 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:[email protected] 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:
- **domain**: `vendor-domain.com` (matches from/to/cc on the org)
- **participant**: `from:[email protected] OR to:…`
- **project code**: any internal tag the sender uses (e.g. `1233V`)
2. **Collect message IDs** from `search --json` (snippet-only) and curate the in-scope set out of the noise.
3. **Fetch full bodies** with a `read --json` loop (one file per message).
4. **Group by `threadId`** client-side — Gmail's list/search APIs return individual messages, _not_ threads; you reconstruct threads yourself.
5. **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.
6. **Pull attachments** for any message whose `attachments[]` is non-empty.
```bash
# 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:**
- `--to` - Recipient email address
- `--subject` - Email subject line
- `--body` OR `--body-file` - Email body text (one of the two)
**Optional:...
© terrylica · MIT · terrylica/cc-skills