Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Reading Gmail

Use gog to search Gmail, page through results, open messages and threads, list labels, and download attachments. The JSON field descriptions support 2 scripts at the end of the chapter, one that reports unread mail and one that saves attachments from matching threads.

Every command in this chapter needs a signed-in account (see Authentication and Accounts), so the chapter shows the commands and describes their output from the documentation and the source of v0.48.1. The examples use --account you@example.com; with GOG_ACCOUNT set or a default account configured you can leave it out. The placeholders MESSAGE_ID, THREAD_ID and ATTACHMENT_ID stand for the opaque identifiers that Gmail assigns and that the search commands print.

Threads and messages

Gmail stores messages, single emails, and groups them into threads, the conversations that the Gmail web interface shows as 1 row. Each message has a message ID and the ID of the thread it belongs to. gog has a search command for each level:

CommandReturnsOne row perJSON list key
gog gmail search QUERYthreadsconversationthreads
gog gmail messages search QUERYmessagesemailmessages

Thread search returns matching conversations. Message search returns individual matching emails and can include their bodies, recipients, headers, and attachment details.

Both take the same query language and the same paging flags (docs/gmail-workflows.md). gog gmail search has the aliases find, query, ls and list.

gog --account you@example.com gmail search 'is:unread newer_than:7d'
gog --account you@example.com gmail search 'from:friend@example.com' --max 25 --json
gog --account you@example.com gmail messages search 'from:friend@example.com newer_than:30d' --json

Query syntax

The query is Gmail’s own search language, the same text you would type into the search box in Gmail on the web. Gmail defines the operators, and gog passes them through. gog joins all positional words with spaces and sends the result to the Gmail API as the search parameter q (internal/cmd/gmail_search.go). The operators used in gog’s documentation and in this book, with the meaning Gmail gives them, are:

OperatorMatches
is:unreadunread messages
newer_than:7dmessages from the last 7 days
from:friend@example.com, to:you@example.comsender or recipient
in:inbox, -in:inboxmessages in the inbox, or outside it
label:Receipts, -label:Receiptsmessages with or without a label
subject:"quarterly report"a phrase in the subject
has:attachmentmessages with attachments
list:example.commailing-list messages from that list domain

Put the whole query in single quotes so that the shell passes it as 1 argument and does not expand characters such as * or $. A double-quoted part inside the query, such as subject:"quarterly report", is a phrase for Gmail. A quoted operator such as "is:unread" is a literal phrase too, so it searches for that text.

For a plain positive system label such as in:inbox or is:unread, gog also sends the matching label ID next to the query, which makes Gmail apply that condition strictly. It leaves negated terms and queries with OR to Gmail (internal/cmd/gmail_search_labels.go).

Queries that start with a minus sign

A query that begins with - looks like a flag to the command-line parser, even inside quotes:

$ gog --account you@example.com --json gmail search '-in:inbox'
unknown flag -i, did you mean one of "-h", "-a", "-j", "-p", "-n", "-y", "-v", "-z"?
{"error":{"class":"usage","code":2,"message":"unknown flag -i, did you mean one of \"-h\", \"-a\", \"-j\", \"-p\", \"-n\", \"-y\", \"-v\", \"-z\"?"}}

Write -- before the query and put every flag before --. Everything after it is query text:

gog --account you@example.com gmail search --max 5 --json -- '-in:inbox newer_than:7d'

Searching by contact

--from-contact NAME on gog gmail search looks the name up in your Google Contacts and adds a from: condition with that person’s addresses to the query. It reads your contacts through the Google People API, so the account also needs Contacts authorization.

Paging, counting and empty results

A search returns at most --max items per call (default 10, and the value must be greater than 0). When more exist, the JSON envelope (the object that wraps the result list) carries a nextPageToken, and in human mode gog prints a hint on stderr: # More results: use --all/--all-pages to fetch every page, or --page TOKEN for the next page.

gog --account you@example.com gmail search 'in:inbox' --max 50 --page NEXT_PAGE_TOKEN
gog --account you@example.com gmail search 'in:inbox' --all --json --results-only
FlagEffect
--max Npage size, 10 by default
--page TOKENcontinue from a nextPageToken
--all (alias --all-pages)follow every page and return 1 combined list
--countadd the size of the whole result set: totalMatches when exact, totalMatchesAtLeast when only a lower bound is known; not available with --results-only
--ids-onlyreturn only IDs and skip the per-item detail requests
--fail-emptyexit with code 3 when nothing matches
--oldestthread search only: show the date of the first message of each thread instead of the last
-z ZONE, --timezone ZONEthe IANA time zone name, such as America/Toronto, used for displayed dates; the default comes from GOG_TIMEZONE, then the configuration, then the system

The JSON envelope of both searches also has count, the number of items returned in this response, and has_more, which is true when a nextPageToken exists. Use --count to get the match count from the server.

gog --account you@example.com gmail search 'is:unread' --count --max 1 --json
gog --account you@example.com gmail search 'is:unread' --fail-empty --json

Without --ids-only, gog makes 1 extra API request per result to fetch headers and labels. For bulk work that needs only identifiers, --ids-only makes 1 request per page; combine it with --max 500, the largest page Gmail allows (docs/gmail-workflows.md):

gog --account you@example.com gmail messages search 'list:example.com' --all --max 500 --ids-only --json --results-only

Fields of the search results

gog selects the fields it prints from each Gmail API response (internal/cmd/gmail_thread_search_helpers.go, internal/cmd/gmail_messages.go). Empty fields are left out of the JSON.

A thread item from gog gmail search has these fields:

FieldMeaning
idthread ID
datedate of the last message (first with --oldest), as YYYY-MM-DD HH:MM in the display time zone, without an offset
internalDateIsothe same message’s Gmail timestamp as an RFC 3339 value (date, time and UTC offset, such as 2026-12-03T14:00:00-05:00)
from, subjecttaken from the first message of the thread
labelslabel names of the first message
messageCountnumber of messages in the thread

A message item from gog gmail messages search has id, threadId, date, internalDateIso, from, subject and labels, plus optional fields that appear only when you ask for them:

FlagAdds
--include-recipientsto, cc, bcc
--headers List-Id,Senderheaders, a map from the canonical header name to its first value
--include-bodybody, the decoded text (see “Body formats” below)
--include-attachmentsattachments, a list of attachment descriptions

date comes from the sender’s Date header, which senders can set to anything, while internalDateIso is the time Gmail recorded. Scripts that sort or compare times should read internalDateIso. With --ids-only, thread items have only id and message items only id and threadId.

The human and plain tables show the columns ID, DATE, FROM, SUBJECT, LABELS and THREAD for threads (the last column shows [N msgs] for threads with more than 1 message), and ID, THREAD, DATE, FROM, SUBJECT, LABELS for messages.

Reading a message

An RFC 822 message consists of header lines, a blank line, and a body. MIME extends that format so that 1 message can hold several typed parts, such as a plain-text body, an HTML body and attachments.

gog gmail get MESSAGE_ID fetches 1 message. --format chooses how much Gmail returns:

--formatContent
full (default)headers, the MIME structure and the body
metadataheaders only; --headers From,Subject limits which ones
rawthe complete message as stored, in RFC 822 form
gog --account you@example.com gmail get MESSAGE_ID
gog --account you@example.com gmail get MESSAGE_ID --format metadata --headers From,Subject,List-Id --json
gog --account you@example.com gmail get MESSAGE_ID --format raw --json

In text mode the command prints labeled lines: id, thread_id, label_ids, from, to, cc, bcc, subject, date, an unsubscribe link when the message has one, the attachments, and the body. In JSON mode the top-level keys are (internal/cmd/gmail_get.go):

KeyContent
messagethe Gmail API message resource: id, threadId, labelIds, snippet, payload with the MIME parts, and raw for --format raw
headersa flat map with the keys from, reply_to, to, cc, bcc, subject, date, message_id, in_reply_to, references
bodythe best text part, decoded (format full only)
attachmentsattachment descriptions (formats full and metadata)
unsubscribethe preferred unsubscribe link, when present

The flat headers map saves you from searching message.payload.headers for a name: jq -r '.headers.subject' is enough. For --format raw, message.raw holds the message in base64url, a text encoding of binary data that uses only characters safe in URLs; decode it to get the exact bytes Gmail stores.

gog gmail raw MESSAGE_ID prints the Gmail API response without any processing, which is useful when you need a field gog does not flatten. Its --format also accepts minimal, and --pretty indents the JSON.

Reading a thread

gog gmail thread get THREAD_ID (the group also has the aliases threads and read) fetches a conversation with all its messages (internal/cmd/gmail_thread.go). In text mode, long bodies are shortened unless you add --full. In JSON mode the result has 2 keys: thread, the Gmail API thread resource with its messages list, and downloaded, the files written when you also pass --download.

gog --account you@example.com gmail thread get THREAD_ID
gog --account you@example.com gmail thread get THREAD_ID --full
gog --account you@example.com gmail thread get THREAD_ID --sanitize-content --json

To open a thread in the browser, gog gmail url prints the web address. It works offline, since it only formats the ID:

$ gog --account you@example.com gmail url THREAD_ID
THREAD_ID	https://mail.google.com/mail/?authuser=you%40example.com#all/THREAD_ID

Body formats and sanitized content

An email often contains the same text twice, once as plain text and once as HTML, in separate MIME parts. gog picks 1 of them for the body field:

  • gog gmail get puts the best text part into body.
  • gog gmail messages search --include-body decodes each body; --body-format text (the default) prefers the plain part and --body-format html the HTML part. --full implies --include-body and turns off the truncation of very long bodies in text output.
  • --format raw on gmail get skips the selection and gives you the stored message.
gog --account you@example.com gmail messages search 'newer_than:7d' --include-body --body-format text --json
gog --account you@example.com gmail messages search 'newer_than:7d' --include-recipients --headers List-Id,Sender --json

Sanitized content is a reduced form of a message intended for logs and AI agents. --sanitize-content strips HTML, removes http and https links, cleans the header text, and drops the raw Gmail payload from JSON. It is available on gmail get, gmail thread get and gmail messages search, and it cannot be combined with --format raw or with --body-format html. A sanitized message keeps id, threadId, labelIds, snippet, internalDate, sizeEstimate, headers, body and attachments (internal/cmd/gmail_sanitize.go). For gmail get it sits under the key message, and --results-only prints it directly:

gog --account you@example.com gmail get MESSAGE_ID --sanitize-content --json --results-only
gog --account you@example.com gmail messages search 'newer_than:7d' --include-body --sanitize-content --json

Mail is written by other people, and an agent that reads it may follow instructions hidden in it. The global flag --wrap-untrusted marks fetched text in JSON with markers that say “external content”, and --readonly blocks every request that would change the mailbox, as Safety Controls for Scripts and Agents explains. A careful read command for an agent looks like this:

gog --account you@example.com --readonly --wrap-untrusted gmail get MESSAGE_ID --sanitize-content --json

Labels

A label is Gmail’s tag for messages; a message can carry several, and folders such as the inbox are labels too. Gmail defines system labels with fixed upper-case IDs, among them INBOX, UNREAD, STARRED, IMPORTANT, SENT, DRAFT, SPAM and TRASH. Labels you create get IDs that Gmail assigns, next to the names you chose.

gog --account you@example.com gmail labels list
gog --account you@example.com gmail labels list --json --results-only
gog --account you@example.com gmail labels get INBOX

gog gmail labels list prints a table with the columns ID, NAME and TYPE (internal/cmd/gmail_labels.go). Its JSON is {"labels": [...]} with the Gmail API label resources. gog gmail labels get accepts an ID or a name and adds the counters messages_total, messages_unread, threads_total and threads_unread in text mode; in JSON they are under label with the API names messagesTotal, messagesUnread, threadsTotal and threadsUnread.

Commands that take labels accept names or IDs, so label:Receipts in a query and --add Receipts on a modify command both work. Changing labels is a write operation and belongs to Writing Gmail.

Attachments

An attachment description, in search results, gmail get output and the attachment commands, has these fields (internal/cmd/gmail_attachments.go):

FieldMeaning
filenamethe filename in the message
size, sizeHumansize in bytes, and the same size in a human-readable format
mimeTypecontent type, such as application/pdf
attachmentIdGmail’s opaque ID, needed to download the file
attachmentIndex0-based position, present with --use-indexed-attachment-ids

Gmail issues a new attachmentId each time it returns a message, so read it from the same response you act on. --use-indexed-attachment-ids (or GOG_GMAIL_USE_INDEXED_ATTACHMENT_IDS=1) replaces these IDs with stable indexes 0, 1, 2 in the output, download arguments, and saved filenames.

Search with --include-attachments to find files, then use 1 of 3 download commands:

gog --account you@example.com gmail messages search 'has:attachment newer_than:30d' --include-attachments --json
gog --account you@example.com gmail thread attachments THREAD_ID
gog --account you@example.com gmail thread attachments THREAD_ID --download --out-dir ./downloads
gog --account you@example.com gmail thread get THREAD_ID --download --out-dir ./downloads
gog --account you@example.com gmail attachment MESSAGE_ID ATTACHMENT_ID --out ./downloads/report.pdf
gog --account you@example.com gmail attachment MESSAGE_ID 0 --use-indexed-attachment-ids --out ./downloads/
  • gog gmail thread attachments THREAD_ID lists every attachment of a thread; --download saves them all into --out-dir, the current directory by default. Its JSON is {"threadId": ..., "attachments": [...]}.
  • gog gmail thread get THREAD_ID --download prints the thread and saves its attachments in 1 step.
  • gog gmail attachment MESSAGE_ID ATTACHMENT_ID saves 1 file. --out names the path, --name sets the filename when --out is a directory or empty, and --inline also returns the content in base64 as contentBase64 for files up to --inline-max-bytes (3,145,728 bytes by default).

Use --dry-run to preview the file destinations before downloading. Without --out, gmail attachment writes into a gmail-attachments folder in the gog configuration directory:

$ gog --account you@example.com --dry-run --json gmail attachment MESSAGE_ID ATTACHMENT_ID | jq -r .request.path
/tmp/tmp.QMXGhkSyK0/config/gmail-attachments/MESSAGE_ID_ATTACHME_attachment.bin
$ gog --account you@example.com --dry-run --json gmail thread attachments THREAD_ID --download --out-dir ./downloads
{
  "dry_run": true,
  "op": "gmail.thread.attachments.download",
  "request": {
    "download": true,
    "out_dir": "downloads",
    "thread_id": "THREAD_ID",
    "use_indexed_attachment_ids": false
  }
}

Read-only scripts

The first script prints a tab-separated report of unread threads from the last 7 days. It passes --readonly, so it cannot change the mailbox even if someone edits the gog command later, and --no-input, so it never waits for a prompt:

#!/usr/bin/env bash
# Usage: unread-report.sh [ACCOUNT]
set -euo pipefail

account=${1:-you@example.com}

threads=$(gog --account "$account" --no-input --readonly --json \
  gmail search 'is:unread newer_than:7d' --max 50 --results-only)

printf 'THREAD\tMESSAGES\tLAST\tFROM\tSUBJECT\n'
printf '%s\n' "$threads" |
  jq -r '.[] | [.id, .messageCount, .internalDateIso, .from, .subject] | @tsv'

--results-only removes the envelope, so jq receives the bare list of thread items. The script stores the output of gog in a variable before jq sees it. If gog fails, for example with exit code 4 when the login has expired, set -e ends the script with that status, and the error object never reaches jq (Output, Schemas and Dry Runs explains why this order matters).

The second script saves the attachments of up to 20 matching threads, 1 folder per thread. It uses --ids-only because it needs nothing but the thread IDs, and it takes the account from GOG_ACCOUNT:

#!/usr/bin/env bash
# Usage: save-attachments.sh QUERY OUT_DIR
set -euo pipefail

query=$1
out_dir=$2

ids=$(gog --no-input --json gmail search "$query" --max 20 --ids-only --results-only)

mkdir -p "$out_dir"
printf '%s\n' "$ids" | jq -r '.[].id' |
  while IFS= read -r thread_id; do
    gog --no-input --json gmail thread attachments "$thread_id" \
      --download --out-dir "$out_dir/$thread_id" >/dev/null
    echo "saved attachments of $thread_id"
  done
GOG_ACCOUNT=you@example.com ./save-attachments.sh 'from:friend@example.com has:attachment newer_than:30d' ./attachments