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

Introduction

gog is a command-line client for Google Workspace APIs, including Gmail, Google Calendar, Drive, Docs, and Sheets. The gog binary provides machine-readable output and controls that limit which actions a caller can take. The independent gogcli project develops the client in Go and releases it under the MIT License.

This book teaches gog using Gmail and Google Calendar. The examples show how to authorize accounts for both services and how to use gog from scripts and AI agents.

  • Search and read mail from the terminal.
  • Write drafts, reply to messages, and send mail after previewing it.
  • List and manage calendar events.
  • Run gog from shell scripts, scheduled jobs, and agents with read-only tokens, command allowlists, and other safety controls.

What gog looks like

A typical gog command names a service, an action and its arguments, and global flags choose the account and the output format:

gog --account me --json gmail search 'is:unread newer_than:7d' --max 10
gog --account me calendar events --today

Both commands need an authorized account, so they cannot run before you have finished Authentication and Accounts. The first prints JSON that a script can process with jq.

The second lists today’s events in a table. me is an alias for you@example.com, a convention that the whole book uses.

Scope of this book

The book covers these parts of gog:

AreaCommandsChapters
Setup and identitygog auth, gog config, gog versionHow gog Talks to Google, Installation and First Checks, Authentication and Accounts
Output contract--json, --plain, gog schema, --dry-runOutput, Schemas and Dry Runs
Mailgog gmailReading Gmail, Writing Gmail: Drafts, Replies, and Sending
Calendargog calendarGoogle Calendar
Safety and automation--readonly, --gmail-no-send, command allowlists, --no-inputSafety Controls for Scripts and Agents, Automation and Troubleshooting

gog also covers Drive, Docs, Sheets, Slides, Forms, Contacts, Tasks, Chat, Meet, Classroom, Apps Script, Analytics, Search Console, YouTube, Photos, Maps and Google Workspace administration, and it has a generic gog api command for any Google API with a Discovery document. The other services follow the same patterns for accounts, output, and safety. Use gog <service> --help to find their commands.

Version and sources

The book describes gog v0.48.1, built from commit 44364d3 (44364d310173f8fc5aced529ba8633231d533919) of github.com/openclaw/gogcli. Its statements about gog come from that commit: the README.md, the guides in docs/, the generated command pages in docs/commands/, and the Go source where the guides are silent. Links to the source point to the same commit, so they stay valid when the project moves on.

Commands, flags and outputs were checked against a gog binary built from that tag. Commands that work offline (help pages, gog schema, gog auth status, dry runs) are shown with their real output. Commands that need a signed-in Google account are shown without output, and their results are described from gog schema and the documentation.

Check your own version before you start:

gog --version

If it reports a newer version, most of the book still applies, but flags and outputs can differ. Compare against gog <command> --help whenever something does not match.

Who this book is for

The book is written for software engineers who are comfortable in a Unix shell. You should know how to set environment variables, use pipes, and read JSON with jq.

Some experience with OAuth helps but is not required, because the book defines every Google-specific and gog-specific term the first time it uses it. Familiarity with Gmail’s search syntax is useful for the Gmail chapters.

You also need a Google account and permission to create a project in the Google Cloud console. A personal Google account works for everything in this book.

How the chapters build on each other

The chapters are meant to be read in order, because each one relies on the setup or the concepts of the previous ones:

  1. How gog Talks to Google explains the objects between gog and Google: the Cloud project, the OAuth client, scopes, tokens, the keyring, accounts and gog’s files.
  2. Installation and First Checks installs gog and inspects it without any account.
  3. Authentication and Accounts creates the OAuth client and authorizes accounts, including read-only accounts, second accounts and headless machines.
  4. Output, Schemas and Dry Runs covers the output formats, the command schema and previews of write commands, which every later chapter uses.
  5. Reading Gmail searches mail, reads messages and threads, lists labels and downloads attachments.
  6. Writing Gmail: Drafts, Replies, and Sending creates drafts, sends, replies, forwards and changes labels.
  7. Google Calendar lists, creates, updates and deletes events, answers invitations and queries free and busy time.
  8. Safety Controls for Scripts and Agents restricts what gog may do when a program runs it.
  9. Automation and Troubleshooting puts gog into scripts and scheduled jobs and explains how to diagnose failures.
  10. Worked Example and Glossary closes the book with an end-to-end morning brief script and a glossary of the terms used throughout.

If you already have a working gog setup, you can skim chapters 1 to 3, but read chapter 4 before the service chapters and chapter 8 before you hand gog to an agent.

Conventions

  • Identities: you@example.com is your account, with the alias me. you@example.org is a second account, with the alias work. friend@example.com is a correspondent. Replace them with your own addresses.
  • Time zone: Examples that need a time zone use America/Toronto.
  • Commands and output: Every output in the book is copied from a real run of gog v0.48.1. Long URLs are sometimes shortened, and the text says so where that happens.

How gog Talks to Google

A command such as gog gmail search relies on configuration in a Google Cloud project, local files, and credentials in a keyring. This chapter explains how those pieces fit together so you can predict which permissions gog auth add requests, diagnose token failures, choose a keyring backend, and locate gog’s files.

For step-by-step setup instructions, see Authentication and Accounts.

The whole picture

Register gog as an OAuth application in your own Google Cloud project. It then calls Google APIs on behalf of the accounts you authorize. Figure 1.1 shows when each component is used.

Figure 1.1. Blue steps happen once per OAuth client, orange steps once per Google account, and green steps on every command. The purple box is the state that gog keeps on your machine.

The Google side

Google Cloud project and enabled APIs

A Google Cloud project is the container in which Google records your OAuth application, its consent screen and the APIs it may call. gog uses your own project, so the quota and the consent screen your accounts see belong to you.

Each Google API must be enabled in the project before any client can call it. This book uses 2 APIs, the Gmail API (gmail.googleapis.com) and the Google Calendar API (calendar-json.googleapis.com). These are the identifiers that gog auth setup prints when you select the gmail and calendar services.

OAuth client and its JSON credentials

An OAuth client is the registration of one application with Google’s authorization server. It consists of a client ID, which is public, and a client secret. gog expects a client of the type Desktop app, which lets it receive the authorization result on a loopback address such as http://127.0.0.1:<port>/oauth2/callback.

When you create the client in the Cloud console, Google offers it as a JSON file, usually named client_secret_<something>.json. This file is the only thing gog needs from the Cloud console.

gog auth credentials reads it and splits it: the client ID goes into credentials.json in gog’s data directory, and the client secret goes into the keyring, unless you pass --insecure, which keeps the secret in the JSON file. The OAuth clients guide describes the storage rules.

The OAuth consent screen is the page Google shows when an account authorizes your client: it names the app and lists the permissions requested. For personal use, the gog quickstart recommends the user type “External” with your own address as the contact.

The consent screen also has a publishing status, either “Testing” or “In production”. This status matters because of token lifetime. According to the gog quickstart, an External app in Testing receives refresh tokens for user-data scopes that expire after 7 days, which forces you to sign in again every week.

The quickstart’s remedy is to publish the app: on the consent screen’s Audience page, choose “Publish app” and confirm. This moves the app to “In production” without submitting it for Google’s verification.

An unverified app in production still works for your own accounts, but Google shows a warning for sensitive scopes and limits the app to 100 users over its lifetime. If you authorized while the app was in Testing, run gog auth add once more with the same services and --force-consent.

The Cloud console records the publishing status. When gog auth doctor --check encounters invalid_grant, it prompts you to check that the OAuth app is published so its tokens can last longer (auth_doctor.go).

Scopes

A scope is a named permission, written as a URL, that an OAuth client requests for an account. Google shows the requested scopes on the consent screen, and the resulting tokens can do only what those scopes allow.

You rarely type scope URLs with gog. Instead, you name services with --services, and gog maps each service to its scopes. gog auth services prints the full table, including the 2 entries below.

ServiceScopes requested by default
gmailgmail.modify, gmail.settings.basic, gmail.settings.sharing
calendarcalendar

All scope names in the table are short forms of URLs under https://www.googleapis.com/auth/. In addition to the service scopes, gog auth add always requests openid, email and userinfo.email, which let gog confirm which account signed in.

You can narrow the request with 3 options.

  • --readonly on gog auth add asks for read-only scopes. For gmail,calendar, the read-only scopes are gmail.readonly and calendar.readonly. The same flag on any other command blocks mutating API requests at runtime.
  • --gmail-scope chooses the Gmail scopes: full (the default), readonly, send (only gmail.send) or read-send (gmail.readonly plus gmail.send).
  • --services itself: its default value is user, which selects every default user service, from Gmail and Calendar to YouTube and Photos. For this book, always pass --services gmail,calendar so that the consent screen asks only for what you use.

You can preview the exact list before any browser opens: gog --dry-run auth add you@example.com --services gmail,calendar prints the plan, including a scopes array. Authentication and Accounts shows that output.

Refresh tokens and access tokens

OAuth gives gog 2 types of tokens.

TokenWhat it isLifetimeWhere gog keeps it
Refresh tokenA long-lived credential that proves the account approved your clientUntil it is revoked, expires under a policy (such as the 7-day Testing rule), or is replacedThe keyring entry token:<client>:<email>
Access tokenA short-lived credential sent with every API requestAbout 1 hourCached in the same keyring entry, with its expiration

When a command needs to call Google, gog loads the keyring entry, reuses the cached access token if it is still valid, and otherwise exchanges the refresh token for a new access token, which it writes back to the entry (client_auth.go). You never handle access tokens yourself in normal use.

If Google rejects the refresh token, the error contains invalid_grant. gog then reports that the token expired or was revoked and tells you to run gog auth add <email> again. The global flag --access-token (or GOG_ACCESS_TOKEN) bypasses stored tokens entirely: gog uses the token you give it, and the help text warns that such a token expires in about 1 hour with no automatic renewal.

The keyring

A keyring is a store for secrets. gog stores OAuth client secrets, refresh tokens, and cached access tokens there. The backend is chosen by GOG_KEYRING_BACKEND if it is set, otherwise by keyring_backend in config.json, otherwise it is auto.

BackendWhere secrets go
autoThe store that the keyring library finds on the system: Keychain on macOS, Secret Service on Linux, Credential Manager on Windows
keychainOnly the keyring library’s keychain backend, which is the macOS Keychain
fileEncrypted files in the keyring directory under gog’s data directory

The file backend encrypts every entry with a password. gog reads it from GOG_KEYRING_PASSWORD; without that variable it prompts on the terminal, and in a process with no terminal (a service, CI job or agent) it fails with no TTY available for keyring file backend password prompt; set GOG_KEYRING_PASSWORD.

Headless Linux is a special case. With the auto backend on Linux, gog uses the file backend whenever DBUS_SESSION_BUS_ADDRESS is unset or set to disabled:, because Secret Service needs a D-Bus session and would otherwise hang (backend.go). The paths guide recommends exactly that setting for containers and agents, with the password supplied by a secret manager.

The operating system’s keyring groups gog entries under the service name gogcli (or the value of GOG_KEYRING_SERVICE_NAME) regardless of GOG_HOME. A separate GOG_HOME therefore gives you a separate set of tokens only with the file backend.

Accounts, aliases and clients

An account is a Google account email address for which gog holds a refresh token. When a command needs an account, gog takes the first of these that is available (account.go):

  1. The --account flag (short form -a).
  2. The GOG_ACCOUNT environment variable.
  3. The stored default account, which you set in the browser-based account manager, gog auth manage.
  4. The only stored token, if exactly one exists.

If none applies, the command stops with missing --account. The value auto in --account or GOG_ACCOUNT skips the first 2 steps and asks for this automatic choice.

An alias is a short name for an account, such as me for you@example.com or work for you@example.org. gog stores aliases in config.json under account_aliases, and both --account and GOG_ACCOUNT accept them. The names auto and default are reserved.

A client name selects one OAuth client among several, with --client or GOG_CLIENT. The default client is called default and uses credentials.json; a client named work uses credentials-work.json.

Tokens are stored per client, which is why the keyring key contains both the client and the email: token:default:you@example.com. When --client is absent, gog consults the account_clients and client_domains maps in the config, then a credentials file named after the email domain, and finally falls back to default.

Most readers need only the default client. A second client becomes useful when, for example, a Google Workspace organization requires its own Cloud project.

Where gog keeps its files

gog uses 4 directories. The separate data directory lets you sync configuration files as dotfiles without including credentials.

KindContentsLinux defaultWith GOG_HOME=/persist/gogcli
Configconfig.json (aliases, keyring backend, client maps)~/.config/gogcli/persist/gogcli/config
Datacredentials*.json, the file keyring, service-account keys~/.local/share/gogcli/persist/gogcli/data
StateGmail watch cursors, email tracking state~/.local/state/gogcli/persist/gogcli/state
CacheIntermediate files for Gmail backups~/.cache/gogcli/persist/gogcli/cache

For each kind, the first setting that exists wins: GOG_CONFIG_DIR, GOG_DATA_DIR, GOG_STATE_DIR or GOG_CACHE_DIR; then the global flag --home for one invocation; then GOG_HOME; then the matching XDG_*_HOME variable; then the platform default. GOG_HOME, --home and the per-kind variables must be absolute paths. On macOS and Windows, the defaults come from the operating system’s user configuration and cache directories instead of the XDG layout.

Use these 3 commands to find the most common paths. The command gog config path prints the config file, gog auth status prints the config path and the keyring backend, and gog auth doctor prints the file keyring directory. Installation and First Checks runs all 3 on a fresh GOG_HOME.

Installation and First Checks

Install gog and check it before adding Google credentials. Use a temporary home directory to inspect the status, account list, and command schema and learn where to find global flags in the top-level help.

Install gog

The gogcli project distributes a single binary called gog. The install guide lists these methods:

MethodCommand or sourceNotes
Homebrew (macOS, Linux)brew install openclaw/tap/gogcliPrebuilt macOS binaries need macOS 15 or later
Gogo install github.com/openclaw/gogcli/cmd/gog@latestReplace latest with v0.48.1 to match this book
Dockerdocker run --rm ghcr.io/openclaw/gogcli:latest versionRuns as a non-root user. See the container setup below for persistent state.
Windowsgogcli_<version>_windows_amd64.zip or _arm64.zip from the releases pagePut gog.exe on PATH
Release archivesgogcli_<version>_<os>_<arch>.tar.gz for darwin and linux, amd64 and arm64A checksums.txt file accompanies them
Sourcegit clone, then make, then ./bin/gog --versionNeeds the Go version declared in go.mod (Go 1.26.0 or later)

The machine used to test this book installed gog from nixpkgs, where the package is named gogcli. The upstream install guide lists only the methods in the table.

For containers, the install guide recommends a persistent GOG_HOME volume and the encrypted file keyring, which How gog Talks to Google explains. The image runs as a non-root user with UID 10001 and prepares /persist/gogcli for that user:

docker volume create gogcli-state

docker run --rm -it \
  -e GOG_HOME=/persist/gogcli \
  -e GOG_KEYRING_BACKEND=file \
  -e GOG_KEYRING_PASSWORD \
  -v gogcli-state:/persist/gogcli \
  ghcr.io/openclaw/gogcli:latest \
  auth add you@example.com --services gmail,calendar

-e GOG_KEYRING_PASSWORD passes the value from your shell environment without putting the password on the command line. Keep it in your shell session or your CI secret store.

A safety-profile binary compiles command restrictions into the executable for agents. Safety Controls for Scripts and Agents covers it.

To update later, use brew upgrade openclaw/tap/gogcli, pull a newer Docker tag, replace the archive, or run git pull && make in a source checkout. The install guide states that refresh tokens and OAuth clients stay valid across point releases.

Check the version

$ gog --version
v0.48.1 (refs/tags/v0.48.1 1970-01-01T00:00:00Z)

The binary records the version, source reference, and build date at build time. This package records the Unix epoch as its build date, so use the tag to identify the release. gog version prints the same line, and with --json it returns the 3 parts as fields:

$ gog --json version
{
  "commit": "refs/tags/v0.48.1",
  "date": "1970-01-01T00:00:00Z",
  "version": "v0.48.1"
}

Work in a throwaway home

Every check in the rest of this chapter runs against an empty directory, so that it cannot read or change a real setup:

export GOG_HOME=$(mktemp -d)
export DBUS_SESSION_BUS_ADDRESS=disabled:

GOG_HOME moves gog’s config, data, state and cache directories under one root. On a Linux desktop, the second line makes the auto keyring backend use the file keyring inside GOG_HOME.

The desktop’s Secret Service is shared across all gog home directories. In the outputs below, the temporary directory is /tmp/tmp.NRnBLwNcIk; yours will have a different name.

The status view

Run gog with no arguments, and it reports where it is installed and where it would look for its configuration:

$ gog
bin: /nix/store/99c5lzzb0k0jhxgb2x6dwkvnn6cxmbap-gogcli-0.48.1/bin/gog
description: Google Workspace from the terminal
config_path	/tmp/tmp.NRnBLwNcIk/config/config.json
config_exists	false
keyring_backend	auto
keyring_backend_source	default

config_exists false is normal: gog creates config.json only when a command needs to store a setting. keyring_backend_source tells you where the backend choice came from: default, config (from config.json) or env (from GOG_KEYRING_BACKEND).

The top-level help

gog --help has 5 sections.

  1. Usage and build. Usage: gog <command> [flags], followed by the version.
  2. Config. The config file path and the keyring backend, as in the status view.
  3. Flags. The global flags, which every command accepts.
  4. Automation. A short contract for scripts.
  5. Commands. Every top-level command with its aliases.

The global flags fall into a few groups:

PurposeFlags
Choose identity--account (-a), --client, --access-token, --home
Choose output--json (-j), --plain (-p), --results-only, --select, --color
Restrict what runs--readonly, --gmail-no-send, --enable-commands, --enable-commands-exact, --disable-commands, --dry-run (-n)
Control interaction--no-input, --force (-y), --verbose (-v)
Handle fetched content--wrap-untrusted

The Automation block is short enough to quote in full:

Automation:
  Use --json or --plain for stable output; --no-input disables prompts.
  Common read-only commands:
    gog gmail labels list --json --results-only
    gog calendar calendars --json --results-only
    gog drive search <text> --json --results-only
  For exact Drive API filters, add --raw-query to drive search.
  Run "gog schema <command path>" for a targeted machine-readable contract.
  Use "gog help <command>" or "gog <command> --help" for prose help.
  Exit codes: 0 success, 1 error, 2 usage, 3 empty, 4 auth, 5 not found,
    6 denied, 7 rate limited, 8 retryable, 10 config, 11 orphaned,
    130 interrupted.
  Run "gog schema --json" for the complete machine-readable contract.

The command list starts with shortcuts for frequent actions: send (for gmail send), login (for auth add), logout (for auth remove), status (for auth status), me and whoami (for people me), and several Drive shortcuts. Then come the service groups, of which this book uses gmail and calendar, followed by the tools around them: auth, config, schema, mcp, version and completion. Every group has its own help, for example gog gmail --help or gog auth add --help.

Authentication status on a fresh home

gog auth status shows the same configuration facts as the status view; once an account is selected, it also reports the account, its OAuth client and where the client credentials are stored:

$ gog auth status
config_path	/tmp/tmp.NRnBLwNcIk/config/config.json
config_exists	false
keyring_backend	auto
keyring_backend_source	default

gog auth list lists the accounts that have a stored token. On a fresh home there are none:

$ gog auth list
No tokens stored
$ gog --json auth list
{
  "accounts": []
}

In scripts, use JSON so you can test whether the accounts array is empty.

Where the files go

These 3 commands show where gog keeps its files.

$ gog config path
/tmp/tmp.NRnBLwNcIk/config/config.json
$ gog auth keyring
path	/tmp/tmp.NRnBLwNcIk/config/config.json
keyring_backend	auto
source	default
Hint: gog auth keyring <auto|keychain|file>
$ gog auth doctor
ok	config.path	/tmp/tmp.NRnBLwNcIk/config/config.json (optional; not created)
ok	keyring.backend	auto (source: default)
ok	keyring.dir	/tmp/tmp.NRnBLwNcIk/data/keyring
ok	keyring.open	opened
warn	tokens	no OAuth tokens stored
hint	tokens	run `gog auth add <email>`
status	warn

gog auth keyring without an argument reports the backend; with auto, keychain or file it writes that choice to config.json. gog auth doctor checks the configuration and the keyring step by step.

Here the file keyring opened in data/keyring, and the only warning is the missing token, which the next chapter fixes. Adding --check also exchanges every stored refresh token with Google, so use the plain form while you are offline.

As the install guide explains, gog auth doctor exits with code 0 whenever it produces a report, including one with status warn. In a script, test the status field of gog --json auth doctor.

The command schema

gog schema prints a machine-readable description of the command line, generated from the running binary. It is the reference that scripts and agents use to discover commands and flags without parsing help text. Without arguments it covers the whole program, which is several megabytes of JSON:

$ gog schema --json | wc -c
6710376

The document has 4 top-level keys: schema_version, build, automation (output formats, exit codes and the active safety settings) and command (the command tree). Pass a command path to describe one command:

$ gog schema auth status --json | jq '.command | {path, help, usage}'
{
  "path": "gog auth status",
  "help": "Show auth configuration and keyring backend",
  "usage": "auth status"
}
$ gog schema gmail search --json | jq '.command.flags[] | select(.name == "max")'
{
  "name": "max",
  "aliases": [
    "limit"
  ],
  "help": "Max results",
  "type": "int64",
  "default": "10",
  "has_default": true,
  "placeholder": "10"
}

A command object has type, name, path, help, usage and flags, plus aliases, positionals or subcommands where they apply. Output, Schemas and Dry Runs uses the schema in more depth.

Shell completion

gog completion <shell> prints a completion script for bash, zsh, fish or powershell. For Bash, for example:

gog completion bash >> ~/.bash_completion

Authentication and Accounts

Set up gog to use a Google account, then choose read-only access, add a second account, or authorize a headless machine as needed. This chapter also explains how to diagnose common authentication failures and remove an account from gog.

How gog Talks to Google explains Cloud projects, OAuth clients, consent screens, scopes, tokens, and keyrings.

The starting point

On a fresh installation, any command that reads Google data fails before it reaches the network:

$ gog --account you@example.com gmail search 'is:unread'
OAuth client credentials missing (OAuth client ID JSON).
Download from: https://console.cloud.google.com/apis/credentials (Create Credentials → OAuth client ID → Desktop app → Download JSON)
Then run: gog auth credentials <credentials.json> (expected at /tmp/tmp.EfL8KEdyac/data/credentials.json)

The exit code is 10, which the exit-code table in gog --help calls config. gog --account you@example.com calendar events --today fails with the same message. With --json, gog prints the message to stderr as before and also writes an error object to stdout, which a script can parse:

{"error":{"class":"config","code":10,"message":"OAuth client credentials missing (OAuth client ID JSON).\nDownload from: https://console.cloud.google.com/apis/credentials (Create Credentials → OAuth client ID → Desktop app → Download JSON)\nThen run: gog auth credentials <credentials.json> (expected at /tmp/tmp.EfL8KEdyac/data/credentials.json)"}}

The message already outlines the procedure: obtain a Desktop app OAuth client, store it with gog auth credentials, then authorize an account.

About the outputs in this chapter

All outputs in this chapter come from real runs of gog v0.48.1 in a throwaway home with the file keyring, set up like this:

export GOG_HOME=$(mktemp -d)
export DBUS_SESSION_BUS_ADDRESS=disabled:
export GOG_KEYRING_BACKEND=file
export GOG_KEYRING_PASSWORD=demo-password

The test machine has no real OAuth client and cannot sign in to Google. It used a placeholder client file with the client ID 123456789012-demo.apps.googleusercontent.com, and it created 2 accounts with gog auth import and a placeholder refresh token (see Headless and SSH machines). Every local command behaves as it would with real credentials; only commands that contact Google, such as gog auth list --check, would fail.

Step 1: Create the Cloud project and the OAuth client

This part happens in the Google Cloud console, once for each OAuth client. These steps use the same console pages as the gog quickstart and gog auth setup.

  1. Create a project at https://console.cloud.google.com/projectcreate. A project ID must have 6 to 30 characters: lowercase letters, digits and hyphens, starting with a letter. This chapter uses my-gog-project.
  2. Enable the APIs in the API library: the Gmail API and the Google Calendar API.
  3. Configure the consent screen at https://console.cloud.google.com/auth/branding. Choose the user type External and enter your own address as the contact.
  4. Publish the app on the Audience page with “Publish app” and “Confirm”, so that refresh tokens do not expire after 7 days. How gog Talks to Google explains why.
  5. At https://console.cloud.google.com/auth/clients, add a client of type Desktop app. Download the JSON file Google provides. Its name usually starts with client_secret_.

Store the downloaded file securely because it contains the client secret.

Step 2 (optional): Let gog auth setup guide you

gog auth setup turns the console steps into a checklist for your project and services. Without the Google Cloud CLI (gcloud) installed, it changes nothing and prints the remaining steps:

$ gog auth setup you@example.com --gcloud-project my-gog-project --services gmail,calendar
status	guided
project	my-gog-project
services	gmail,calendar
apis	calendar-json.googleapis.com,gmail.googleapis.com
next_1	Install gcloud, or create/select a Google Cloud project manually
next_2	Configure OAuth consent: https://console.cloud.google.com/auth/branding?project=my-gog-project
next_3	Create a Desktop OAuth client and download its JSON: https://console.cloud.google.com/auth/clients?project=my-gog-project
next_4	Store the download with `gog auth credentials /path/to/client_secret.json`
next_5	Authorize with `gog auth add you@example.com --services gmail,calendar`
next_6	Verify with `gog auth doctor --check`

When gcloud is installed and authenticated, these flags automate parts of the setup (auth_setup.go):

FlagEffect
--create-projectCreates the project named by --gcloud-project, after asking for confirmation
--enable-apisEnables the APIs of the selected services with gcloud services enable
--open-consoleOpens the OAuth client page of the project in the browser
--credentials <file>Stores the downloaded client JSON, like gog auth credentials
--loginContinues with the browser authorization of the given account

The consent screen and the Desktop OAuth client still have to be created in the console. Add --dry-run to see the plan without changing anything; the plan lists the API identifiers that --enable-apis would enable, here calendar-json.googleapis.com and gmail.googleapis.com.

Step 3: Store the OAuth client

Give gog the downloaded file:

gog auth credentials ~/Downloads/client_secret_*.json

gog auth credentials <file> is a shortcut for gog auth credentials set <file>. Pass - to read the JSON from standard input. In the test home, with the placeholder client file in the current directory:

$ gog auth credentials client_secret.json
path	/tmp/tmp.EfL8KEdyac/data/credentials.json
client	default
client_secret_in_keyring	true
$ gog auth credentials list
CLIENT   PATH                                       SECRET_KEYRING  DOMAINS
default  /tmp/tmp.EfL8KEdyac/data/credentials.json  true
$ cat "$GOG_HOME/data/credentials.json"
{
  "client_id": "123456789012-demo.apps.googleusercontent.com"
}

The stored credentials.json contains only the client ID. gog stores the client secret in the keyring. After this step you can delete or archive the downloaded file.

Step 4: Authorize an account

Authorize your account for the 2 services this book uses.

gog auth add you@example.com --services gmail,calendar

gog starts a temporary listener on a loopback address, opens the consent page in your browser, and waits (quickstart). You sign in as you@example.com, review the requested permissions and approve them.

Google then redirects the browser back to the listener, and gog stores the resulting refresh token in the keyring. The address must belong to a Google account; a mailbox at another provider cannot complete Google’s sign-in.

The top-level command gog login you@example.com is a shortcut for gog auth add.

Preview the request

Before any browser opens, --dry-run shows exactly what gog would request:

$ gog --dry-run auth add you@example.com --services gmail,calendar
Dry run: would auth.add
{
  "client": "default",
  "drive_scope": "full",
  "email": "you@example.com",
  "extra_scopes": null,
  "force_consent": false,
  "gmail_scope": "full",
  "listen_addr": "",
  "manual": false,
  "readonly": false,
  "redirect_host": "",
  "redirect_uri": "",
  "remote": false,
  "scopes": [
    "email",
    "https://www.googleapis.com/auth/calendar",
    "https://www.googleapis.com/auth/gmail.modify",
    "https://www.googleapis.com/auth/gmail.settings.basic",
    "https://www.googleapis.com/auth/gmail.settings.sharing",
    "https://www.googleapis.com/auth/userinfo.email",
    "openid"
  ],
  "services": [
    "gmail",
    "calendar"
  ],
  "step": 0
}

Read-only and narrower Gmail access

For a script or agent that only reads Google data, authorize the account with read-only scopes. Put the global flag --readonly before auth add:

$ gog --readonly --dry-run --json auth add you@example.com --services gmail,calendar | jq '.request.scopes'
[
  "email",
  "https://www.googleapis.com/auth/calendar.readonly",
  "https://www.googleapis.com/auth/gmail.readonly",
  "https://www.googleapis.com/auth/userinfo.email",
  "openid"
]

For Gmail alone, --gmail-scope offers finer modes. These are the scope lists gog printed for each mode with --services gmail:

--gmail-scopeGmail scopes requested
full (default)gmail.modify, gmail.settings.basic, gmail.settings.sharing
readonlygmail.readonly
sendgmail.send
read-sendgmail.readonly, gmail.send

The scope limit applies to every program that uses the token. Combine it with the runtime controls in Safety Controls for Scripts and Agents for defense in depth.

Changing the scopes of an existing account

Run gog auth add again for the same account with the complete set of services and modes you want, and add --force-consent so that Google shows the consent screen and issues a new refresh token. A bare --force-consent without --services falls back to the default service set, so check what the account has first with gog --json auth list, which records the services of each token.

Inspect what you have

The listings in this section already show the second account, you@example.org, and the aliases me and work, which the next 2 sections create.

Supported services

gog auth services prints every service with its scopes and APIs. The JSON form is easier to filter:

$ gog --json auth services | jq '.services[] | select(.service == "gmail" or .service == "calendar")'
{
  "service": "gmail",
  "user": true,
  "scopes": [
    "https://www.googleapis.com/auth/gmail.modify",
    "https://www.googleapis.com/auth/gmail.settings.basic",
    "https://www.googleapis.com/auth/gmail.settings.sharing"
  ],
  "apis": [
    "Gmail API"
  ]
}
{
  "service": "calendar",
  "user": true,
  "scopes": [
    "https://www.googleapis.com/auth/calendar"
  ],
  "apis": [
    "Calendar API"
  ]
}

user: true marks the services that the default --services user includes.

Stored accounts

gog auth list prints one line per stored token: the email, the OAuth client, the recorded services, the creation time and the kind of authentication.

$ gog auth list
you@example.com	default	gmail,calendar	2026-11-28T02:17:15Z	oauth
you@example.org	default	gmail,calendar	2026-11-28T02:17:15Z	oauth
$ gog auth tokens list
token:default:you@example.com
token:default:you@example.org

gog auth tokens list shows the keyring keys, which follow the pattern token:<client>:<email>. Add --check to gog auth list to exchange each refresh token with Google and report the ones that no longer work.

Status and diagnosis

gog auth status reports the configuration and, when an account is selected, the account’s client and credential files:

$ GOG_ACCOUNT=work gog auth status
config_path	/tmp/tmp.EfL8KEdyac/config/config.json
config_exists	true
keyring_backend	file
keyring_backend_source	env
account	you@example.org
client	default
credentials_path	/tmp/tmp.EfL8KEdyac/data/credentials.json
credentials_exists	true
client_secret_in_keyring	true
auth_preferred	oauth
service_account_configured	false

gog auth doctor walks through the configuration, the keyring and every token, and gives a hint for each problem:

$ gog auth doctor
ok	config.path	/tmp/tmp.EfL8KEdyac/config/config.json
ok	keyring.backend	file (source: env)
ok	keyring.dir	/tmp/tmp.EfL8KEdyac/data/keyring
ok	keyring.password	GOG_KEYRING_PASSWORD is set
hint	keyring.password	keep this value identical across shell, service, and agent configs
ok	keyring.open	opened
ok	tokens	2 readable OAuth tokens of 2 stored token accounts
ok	credentials.default	OAuth client credentials available
status	ok

With --check, doctor also exchanges every refresh token with Google, which is the real test after gog auth add. In scripts, read the status field of gog --json auth doctor --check; the command exits with 0 even when it reports errors.

Aliases and GOG_ACCOUNT

Typing full addresses in every command is tedious, and hard-coding them in scripts spreads personal data. An alias gives each account a short, stable name:

$ gog auth alias set me you@example.com
alias	me
email	you@example.com
$ gog auth alias set work you@example.org
alias	work
email	you@example.org
$ gog auth alias list
ALIAS  EMAIL
me     you@example.com
work   you@example.org
$ cat "$GOG_HOME/config/config.json"
{
  "account_aliases": {
    "me": "you@example.com",
    "work": "you@example.org"
  }
}

gog auth alias unset <alias> removes one. The names auto and default are reserved (auth_alias.go):

$ gog auth alias set auto you@example.com
alias name is reserved

An alias works anywhere an account is expected: gog --account work gmail search 'is:unread', or GOG_ACCOUNT=me in the environment. With 2 accounts stored and neither --account nor GOG_ACCOUNT set, gog refuses to guess:

$ gog gmail search 'is:unread'
missing --account (or set GOG_ACCOUNT, set default via `gog auth manage`, or store exactly one token)

The message lists all 4 sources in precedence order. gog auth manage (also reachable as gog auth login) opens a local account manager in the browser, where you can mark one account as the default.

For an interactive shell, export GOG_ACCOUNT=me sets the account for the session. In scripts, pass --account so each command specifies the account it uses.

A second account

Adding another account repeats Step 4 with a different address:

gog auth add you@example.org --services gmail,calendar
gog auth alias set work you@example.org
gog --account work calendar events --today

Both accounts use the default OAuth client unless you select another one. When an account should go through a different Cloud project, for example one that a Google Workspace organization manages, store that project’s client under a name of its own and map the account’s domain to it:

$ gog --client work auth credentials client_secret.json --domain example.org
path	/tmp/tmp.NDzVqBPFR7/data/credentials-work.json
client	work
client_secret_in_keyring	true
$ gog auth credentials list
CLIENT   PATH                                            SECRET_KEYRING  DOMAINS
default  /tmp/tmp.NDzVqBPFR7/data/credentials.json       true
work     /tmp/tmp.NDzVqBPFR7/data/credentials-work.json  true            example.org
$ gog --dry-run --json auth add you@example.org --services gmail,calendar | jq -r '.request.client'
work

The --domain option writes client_domains into config.json, so every @example.org account now selects the work client without --client. This listing comes from a separate home that held only those 2 clients. The OAuth clients guide gives the full resolution order.

Set up the domain mapping before authorizing accounts in that domain. From the moment the mapping exists, gog resolves you@example.org to the work client. In a test where the token had been stored under default first, gog --force auth remove you@example.org afterward reported client work and left the default token in place.

Headless and SSH machines

A server, a container or a remote shell usually has no browser, and often no desktop keyring. gog supports 4 ways to set up authentication on these machines.

The manual flow

gog auth add you@example.com --services gmail,calendar --manual

gog prints an authorization URL to stderr. Open it in a browser on any machine and approve the request.

Google then redirects to a loopback URL, which fails to load because no listener runs on that machine; copy the full URL from the address bar and paste it at gog’s prompt, Paste redirect URL (Enter or Ctrl-D): (oauth_flow_manual.go). Manual flows wait 5 minutes by default, which --timeout changes.

The 2-step remote flow

When the command cannot stay open while you switch to a browser (for example, in an automation that runs one command at a time), split the flow:

$ gog auth add you@example.com --services gmail,calendar --remote --step 1
Google sign-in requires a Google Account or Google Workspace account; if consent fails, retry with explicit --services and preserve existing services when reauthorizing.
auth_url	https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=...
state_reused	false
Run again with the same root flags and --remote --step 2 --auth-url <redirect-url> --services gmail,calendar

The auth_url line is shortened here. Open the full URL, approve, copy the redirect URL from the address bar, and finish with:

gog auth add you@example.com --services gmail,calendar --remote --step 2 --auth-url '<redirect-url>'

Step 1 saves a short-lived verifier in the config directory, so step 2 must run with the same GOG_HOME and the same --client (OAuth clients guide). When the browser can reach the server directly, --listen-addr, --redirect-host and --redirect-uri let you choose where gog listens and which callback URL it registers.

Moving or importing a refresh token

If the account is already authorized on another machine, you can copy its refresh token without another sign-in.

$ gog auth tokens export you@example.com --out exported-token.json
WARNING: exported file contains OAuth tokens (keep it safe and delete it when done)
exported	true
email	you@example.com
client	default
path	exported-token.json
$ jq keys exported-token.json
[
  "client",
  "created_at",
  "email",
  "refresh_token",
  "services"
]

On the target machine, store the same OAuth client first, then import the file:

$ gog auth credentials client_secret.json
path	/tmp/tmp.AJhJ1RnTLe/data/credentials.json
client	default
client_secret_in_keyring	true
$ gog auth tokens import exported-token.json
Imported refresh token into keyring
imported	true
email	you@example.com
client	default
$ gog auth list
you@example.com	default	gmail,calendar	2026-11-28T02:17:15Z	oauth

gog needs the client ID and secret of the client named in the file to exchange the refresh token, which is why the client file comes first. Delete the exported file as soon as the import succeeds.

Use gog auth import to load a refresh token from a secret manager. Exactly one of --refresh-token-env, --refresh-token-file and --refresh-token-stdin supplies it:

$ gog auth import --email you@example.com --refresh-token-env DEMO_REFRESH_TOKEN --services gmail,calendar
imported	true
client	default
email	you@example.com

gog auth list displays the services recorded by --services. The token retains the scopes it was originally granted. gog auth import refuses to overwrite an existing entry unless you add --force.

The file keyring and its password

Without a desktop session there is no Secret Service, and the file keyring takes its place. You can select it explicitly in the environment or once in the configuration:

$ gog auth keyring file
NOTE: file keyring backend in non-interactive context requires GOG_KEYRING_PASSWORD
written	true
path	/tmp/tmp.34PorqgVFD/config/config.json
keyring_backend	file

This output comes from another throwaway home in which GOG_KEYRING_BACKEND was unset; when the variable is set, gog adds a note that it overrides config.json. Every process that runs gog must receive the same GOG_KEYRING_PASSWORD: your shell, a systemd service, a CI job and an agent’s subprocesses. When the variable is missing, doctor shows the failure clearly:

$ env -u GOG_KEYRING_PASSWORD gog auth doctor
ok	config.path	/tmp/tmp.EfL8KEdyac/config/config.json
ok	keyring.backend	file (source: env)
ok	keyring.dir	/tmp/tmp.EfL8KEdyac/data/keyring
error	keyring.password	file keyring selected but GOG_KEYRING_PASSWORD is not set in a non-interactive process
hint	keyring.password	set GOG_KEYRING_PASSWORD or switch to a system keyring
ok	keyring.open	opened
error	token.default.you@example.com	read token: read encoded file keyring item: no TTY available for keyring file backend password prompt; set GOG_KEYRING_PASSWORD
hint	token.default.you@example.com	file keyring needs GOG_KEYRING_PASSWORD in non-interactive shells, services, CI, and agents
error	token.default.you@example.org	read token: read encoded file keyring item: no TTY available for keyring file backend password prompt; set GOG_KEYRING_PASSWORD
hint	token.default.you@example.org	file keyring needs GOG_KEYRING_PASSWORD in non-interactive shells, services, CI, and agents
ok	tokens	0 readable OAuth tokens of 2 stored token accounts
status	error

A minimal environment for a headless service therefore contains GOG_HOME, GOG_KEYRING_BACKEND=file and GOG_KEYRING_PASSWORD, the last one injected from a secret store and never written into a script or an image (install guide). Test from the same entry point that the service uses, because a command that works in your login shell proves only that your shell has the password. To change the password later, gog auth rekey writes a re-encrypted copy of the keyring, as described in the paths guide.

Removing an account

gog auth remove deletes an account’s token. It is a destructive command, so in a non-interactive shell it asks for --force, and --dry-run shows what it would do:

$ gog auth remove you@example.org
refusing to remove stored token for you@example.org without --force (non-interactive)
$ gog --dry-run auth remove you@example.org
Dry run: would auth.remove
{
  "email": "you@example.org"
}
$ gog --force auth remove you@example.org
deleted	true
email	you@example.org
client	default
$ gog auth alias list
ALIAS  EMAIL
me     you@example.com
$ gog auth list
you@example.com	default	gmail,calendar	2026-11-28T02:17:15Z	oauth

Along with the token, gog removed the alias work, which pointed to the removed account, and the account’s client mapping in config.json (auth_accounts.go). The top-level gog logout <email> is a shortcut for the same command.

gog auth remove deletes the local token. To revoke the OAuth grant, withdraw access in your Google Account. To remove the OAuth client from gog as well, run gog auth credentials remove (the default client) or gog auth credentials remove work for a named client.

Output, Schemas and Dry Runs

gog supports 3 output formats for command results: human-readable text, JSON, and tab-separated text. This chapter covers selecting a format, filtering JSON, inspecting commands with gog schema, handling exit codes, and supplying date and time arguments.

Use --dry-run to preview a write request without contacting Google. The final examples use jq to inspect the plan.

All output in this chapter comes from gog v0.48.1 running with an empty configuration directory, so nothing here needs a Google account. To reproduce it, start a shell with a throwaway home:

export GOG_HOME="$(mktemp -d)"
cd "$(mktemp -d)"
printf 'Hello,\n\nThe agenda for Monday is attached.\n' > note.txt
printf 'Agenda\n1. Budget review\n2. Hiring plan\n' > agenda.txt

GOG_HOME moves the root of the gog configuration, data, state and cache directories to that directory (see Installation and First Checks). The 2 text files are used by the Gmail examples below.

Output modes

gog writes the result of a command to standard output (stdout) and everything else, such as prompts, progress messages, warnings and hints, to standard error (stderr). Standard output supports these 3 formats.

ModeFlagShapeUse it for
Humannonealigned table or labeled lines, color when the terminal supports itreading at the terminal
JSON--json or -j1 JSON document, pretty-printedscripts, jq, AI agents
Plain--plain or -ptab-separated values (TSV) with a header row, no colorcut, awk, sort, spreadsheets

The rule in docs/automation.md is simple: anything a program reads should use --json or --plain, because the human layout can change. gog auth services works without an account, so it is a convenient way to compare the modes. The human table pads its columns with spaces:

$ gog auth services | cut -c 1-36 | sed 's/ *$//' | head -n 3
SERVICE        USER   APIS
gmail          true   Gmail API
calendar       true   Calendar API

The plain form separates the same columns with tabs, so cut -f selects them reliably:

$ gog auth services --plain | cut -f 1,3 | head -n 4
SERVICE	APIS
gmail	Gmail API
calendar	Calendar API
chat	Chat API

Choose 1 machine-readable format per command. Requesting both produces a usage error with exit code 2.

$ gog --json --plain auth services
invalid output mode (cannot combine --json and --plain)
{"error":{"class":"usage","code":2,"message":"invalid output mode (cannot combine --json and --plain)"}}

The environment variables GOG_JSON=1 and GOG_PLAIN=1 set a default mode for every command in a shell, which is convenient in agent sessions. An explicit flag on the command line wins over the environment:

$ GOG_JSON=1 gog auth services --plain | cut -f 1 | head -n 3
SERVICE
gmail
calendar

Color, prompts and confirmations

--color takes auto (the default), always or never, and GOG_COLOR sets the same choice from the environment. In auto mode gog detects whether the output is a terminal. JSON and plain output remain uncolored at every --color setting (internal/cmd/root.go).

A few destructive commands, such as gog calendar delete and gog gmail drafts delete, ask Proceed to ...? [y/N] before they act. --no-input makes commands fail whenever they would otherwise prompt.

gog also refuses to prompt when standard input is not a terminal, so a script gets the same refusal even without the flag. --force (or -y) skips the confirmation (internal/cmd/confirm.go).

$ gog --account you@example.com --no-input calendar delete primary EVENT_ID
refusing to delete event EVENT_ID from calendar primary without --force (non-interactive)

The exit code is 2. Use --no-input in every script, CI job and agent session, so that a missing argument or an unexpected question stops the run instead of waiting forever for an answer.

Shaping JSON with --results-only and --select

Many JSON results are wrapped in an envelope, an object that holds the result list alongside metadata such as nextPageToken (the token for the next page of a list). --results-only removes the envelope and prints only the primary result.

--select keeps only the named fields. It accepts a comma-separated list and dot paths such as request.to.

Both options apply only in JSON mode:

$ gog auth services --json --results-only --select service,user | head -n 9
[
  {
    "service": "gmail",
    "user": true
  },
  {
    "service": "calendar",
    "user": true
  },
$ gog auth services --select service
--select requires --json

--results-only runs before --select, so for a list the selected fields are relative to each item (docs/automation.md). --fields is an alias for --select on commands that have no --fields flag of their own.

Some commands, such as gog calendar events, define their own --fields, which acts as a field mask by specifying the fields the Google API should return. The help page of each command shows which meaning applies.

Errors in JSON mode

When a command fails in JSON mode, gog still writes a JSON document to stdout. It has 1 key, error, whose object holds the numeric code (equal to the exit status), a stable class name, and the message.

The human message also appears on stderr. Here a search fails because this machine has no OAuth client, the application identity gog needs before it can sign in (see Authentication and Accounts):

$ gog --account you@example.com --json gmail search 'is:unread' 2>/dev/null | jq '.error | {class, code}'
{
  "class": "config",
  "code": 10
}

--results-only and --select do not touch the error object, so a script can always read .error.code (docs/automation.md). If a command has already printed part of its result before it fails, gog leaves that output alone and adds no error object, which is why a script should look at the exit status first and at stdout second.

Exit codes

gog uses named exit codes so that scripts can react to a failure without parsing English text. The table lists them as gog schema reports them:

CodeNameWhen gog uses it
0okthe command succeeded
1errora failure that fits no other class
2usagewrong arguments or flags, conflicting options, a blocked or refused operation
3empty_resultsthe query ran but found nothing, and the command was asked to signal that (--fail-empty)
4auth_requiredthe stored login is missing, expired, revoked or unusable
5not_foundthe message, event or other resource does not exist
6permission_deniedthe account is signed in but lacks access
7rate_limiteda Google quota or rate limit was hit
8retryablea temporary server or network failure
10configlocal setup, such as the OAuth client file, is missing
11orphaneda Google Docs comment lost its anchor (not relevant to Gmail or Calendar)
130cancelledthe run was interrupted, for example with Ctrl-C

gog retries rate-limited Google requests with increasing delays before exiting with code 7 (docs/automation.md). The project may add codes later, so every case statement needs a fallback branch. The following script, saved as labels-or-explain.sh, lists Gmail labels and explains the common failures:

#!/usr/bin/env bash
set -u

if output=$(gog --account you@example.com --no-input --json gmail labels list); then
  printf '%s\n' "$output" | jq -r '.labels[].name'
else
  rc=$?
  case $rc in
  4) echo "the token is missing or expired: sign in again" >&2 ;;
  7 | 8) echo "temporary failure: try again later" >&2 ;;
  10) echo "gog has no OAuth client on this machine" >&2 ;;
  *) echo "gog failed with exit code $rc" >&2 ;;
  esac
  exit "$rc"
fi

On a machine without credentials, gog prints its own message on stderr, the script adds its explanation, and the script exits with 10:

$ ./labels-or-explain.sh
OAuth client credentials missing (OAuth client ID JSON).
Download from: https://console.cloud.google.com/apis/credentials (Create Credentials → OAuth client ID → Desktop app → Download JSON)
Then run: gog auth credentials <credentials.json> (expected at /tmp/tmp.xNGZrwgGOu/data/credentials.json)
gog has no OAuth client on this machine

Reading the contract with gog schema

gog schema prints a JSON description of the command tree. Without arguments it covers the whole CLI; with a command path such as gog schema gmail search it describes only that command.

It always prints JSON, and it rejects --plain (docs/automation.md). The top level has 4 keys:

$ gog schema --json | jq -c 'keys'
["automation","build","command","schema_version"]
KeyContent
schema_versionthe version of the schema format (1 in v0.48.1)
buildthe gog version string
commandthe command: name, aliases, path, usage, help, flags, positionals and, for groups, subcommands
automationoutput_formats, exit_codes and safety, the safety settings in force for this invocation

The exit code table above comes from this object:

$ gog schema --json | jq '.automation.exit_codes'
{
  "auth_required": 4,
  "cancelled": 130,
  "config": 10,
  "empty_results": 3,
  "error": 1,
  "not_found": 5,
  "ok": 0,
  "orphaned": 11,
  "permission_denied": 6,
  "rate_limited": 7,
  "retryable": 8,
  "usage": 2
}

Positional arguments, the values written without a flag name, are listed under command.positionals. cumulative means that the argument takes every remaining word:

$ gog schema gmail search | jq '.command | {path, usage, positionals}'
{
  "path": "gog gmail (mail,email) search (find,query,ls,list)",
  "usage": "gmail (mail,email) search (find,query,ls,list) <query> ... [flags]",
  "positionals": [
    {
      "name": "query",
      "help": "Search query",
      "type": "[]string",
      "required": true,
      "cumulative": true
    }
  ]
}

Each flag object can carry name, aliases, short, help, type, default, has_default, enum, envs (environment variables that set it), required and placeholder. The flag list includes the global flags, so --json and --account appear on every command:

$ gog schema gmail search | jq '.command.flags[] | select(.name == "max")'
{
  "name": "max",
  "aliases": [
    "limit"
  ],
  "help": "Max results",
  "type": "int64",
  "default": "10",
  "has_default": true,
  "placeholder": "10"
}

The schema covers the input side of a command: its arguments, flags, exit codes and safety state. The JSON fields that the Gmail and Calendar commands print are described in Reading Gmail, Writing Gmail and Google Calendar, from the documentation and the source code. The safety object is the subject of Safety Controls for Scripts and Agents.

Date and time arguments

docs/dates.md lists the input formats gog accepts where it parses times:

FormExample
Date only2026-12-03
RFC 3339 date and time with offset2026-12-03T14:00:00-05:00 or 2026-12-03T19:00:00Z
ISO offset without colon2026-12-03T14:00:00-0500
Local date and time, no offset2026-12-03T14:00 or 2026-12-03 14:00
Relative (calendar range flags only)now, today, tomorrow, yesterday, monday, next friday

An RFC 3339 timestamp contains a date, the letter T, a time, and a UTC offset. It is the safest choice in scripts because it names one instant without depending on any time zone setting.

The relative words work only in the range flags --from and --to of commands that search a period, such as gog calendar events and gog calendar freebusy. The --from and --to flags for gog calendar create and gog calendar update document RFC3339 as their input format. gog copies the supplied text unchanged into the event. A dry run (next section) shows the effect:

$ gog --account you@example.com --dry-run --json calendar create primary --summary "Check-in" --from tomorrow --to tomorrow | jq '.request.event.start'
{
  "dateTime": "tomorrow"
}

gog did not convert tomorrow into a timestamp. Always pass RFC 3339 values, with an explicit offset, when you create or move an event. Google Calendar explains how range flags choose their time zone.

Dry runs

--dry-run (short form -n, with the aliases --dryrun, --noop and --preview) prints the planned write request and stops before contacting Google. The exit status is 0. In JSON mode the plan has 3 keys: dry_run (always true), op (the operation name, such as gmail.send) and request (the parameters gog collected):

$ gog --account you@example.com --dry-run --json gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt --attach agenda.txt
{
  "dry_run": true,
  "op": "gmail.send",
  "request": {
    "attachments": [
      "agenda.txt"
    ],
    "bcc": null,
    "body_html_len": 0,
    "body_len": 43,
    "cc": null,
    "from": "",
    "reply_all": false,
    "reply_to": "",
    "reply_to_message_id": "",
    "signature": false,
    "signature_file": "",
    "signature_from": "",
    "subject": "Agenda for Monday",
    "thread_id": "",
    "to": [
      "friend@example.com"
    ],
    "track": false,
    "track_split": false
  }
}

The plan records the body as its length in bytes (body_len) and lists attachments by path. An unset recipient field is null, while a set one is a list. The same dry run for a calendar event shows the complete event resource that gog would send:

$ gog --account you@example.com --dry-run --json calendar create primary --summary "Project review" --from 2026-12-03T14:00:00-05:00 --to 2026-12-03T15:00:00-05:00 --timezone America/Toronto --attendees friend@example.com --location "Room 4B" --description "Review the open items before the holidays."
{
  "dry_run": true,
  "op": "calendar.create",
  "request": {
    "calendar_id": "primary",
    "conference_version_1": false,
    "event": {
      "attendees": [
        {
          "email": "friend@example.com"
        }
      ],
      "description": "Review the open items before the holidays.",
      "end": {
        "dateTime": "2026-12-03T15:00:00-05:00",
        "timeZone": "America/Toronto"
      },
      "location": "Room 4B",
      "start": {
        "dateTime": "2026-12-03T14:00:00-05:00",
        "timeZone": "America/Toronto"
      },
      "summary": "Project review"
    },
    "send_updates": "",
    "supports_attachments": false
  }
}

What the other modes print

Use --json when a program needs to parse the full plan. The human-readable form prints a banner on stdout before the request. Plain output puts the request on 1 line as request_json.

$ gog --account you@example.com --dry-run gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt | head -n 3
Dry run: would gmail.send
{
  "attachments": [],
$ gog --account you@example.com --dry-run --plain gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt | cut -c 1-60
dry_run	true
op	gmail.send
request_json	{"attachments":[],"bcc":null,"body_html_len":0,

A dry-run plan ignores --select and --results-only and always prints all 3 keys (internal/cmd/dryrun.go). Use jq to pick fields from it:

$ gog --account you@example.com --dry-run --json --select op gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt | jq -c 'keys'
["dry_run","op","request"]

What a dry run checks

A dry run needs no account and makes no network request, yet it runs most of the local validation. These checks were observed with v0.48.1:

Problem in the commandDry run result
a required flag is missing, such as --subject on gmail drafts createexit 2, required: --subject
a recipient is not an email addressexit 2, invalid --to recipient list ...
--body-file names a file that does not existexit 1, open missing.txt: no such file or directory
an unknown IANA time zone name (a region name such as America/Toronto) in --timezoneexit 2
a send while --gmail-no-send is activeexit 2, Gmail sending is blocked by --gmail-no-send
--attach names a file that does not existnot detected, exit 0
a message, thread or event ID that does not existnot detected, gog does not look it up
a time string that is not RFC 3339 in calendar createnot detected, forwarded as written

A successful dry run confirms that the command passed the local checks that run before the preview. Google can still reject the actual request.

Inspecting a plan with jq

jq is a command-line JSON processor that most package managers provide. Because unset recipient fields are null, a filter that iterates over them must supply an empty list first.

The // operator supplies a default. For example, .cc // [] yields [] when .cc is null.

Without it, jq stops with an error:

$ gog --dry-run --json gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt | jq -r '.request | [.to[], .cc[]] | join(", ")'
jq: error (at <stdin>:25): Cannot iterate over null (null)
$ gog --dry-run --json gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt | jq -r '.request | [.to[], (.cc // [])[], (.bcc // [])[]] | join(", ")'
friend@example.com
$ gog --dry-run --json gmail send --to friend@example.com --cc you@example.org --subject "Agenda for Monday" --body-file note.txt | jq -r '.request | [.to[], (.cc // [])[], (.bcc // [])[]] | join(", ")'
friend@example.com, you@example.org

jq -e sets its own exit status from the last value: 0 for true, 1 for false or null. That turns a filter into a test that a script can use in an if:

$ gog --dry-run --json gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt | jq -e '.op == "gmail.send" and (.request.attachments | length) == 0'
true

The script takes an allowed domain and the flags of a gmail send command, builds the dry-run plan, and refuses when any recipient falls outside the domain.

It never sends anything itself, so you can place it in front of the real command. Save it as check-recipients.sh and make it executable:

#!/usr/bin/env bash
# Usage: check-recipients.sh DOMAIN [gmail send flags...]
set -euo pipefail

domain=$1
shift

plan=$(gog --dry-run --json gmail send "$@")

recipients=$(printf '%s\n' "$plan" | jq -r '
  .request | [(.to // [])[], (.cc // [])[], (.bcc // [])[]] | .[]')

if [ -z "$recipients" ]; then
  echo "no explicit recipients in the plan" >&2
  exit 1
fi

while IFS= read -r address; do
  case $address in
  *@"$domain") ;;
  *)
    echo "refusing: $address is outside $domain" >&2
    exit 1
    ;;
  esac
done <<<"$recipients"

echo "plan ok: $(printf '%s\n' "$recipients" | paste -sd, -)"
$ ./check-recipients.sh example.com --to friend@example.com --cc you@example.com --subject "Agenda for Monday" --body-file note.txt
plan ok: friend@example.com,you@example.com
$ ./check-recipients.sh example.com --to friend@example.com --cc you@example.org --subject "Agenda for Monday" --body-file note.txt
refusing: you@example.org is outside example.com

The second run exits with 1. Safety Controls for Scripts and Agents describes the controls that gog itself enforces, which are stronger than a wrapper script because they cannot be skipped by calling gog directly.

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

Writing Gmail: Drafts, Replies, and Sending

Use gog to create drafts, send messages and replies, forward mail, change labels, archive messages, and move them to the trash. Each command is shown with its --dry-run --json plan, captured from gog v0.48.1 with an empty configuration, so you can see exactly what gog would ask Gmail to do. When a script or agent prepares a message, save it as a draft for someone to review in Gmail before sending.

The dry runs need no account. To reproduce them, prepare a throwaway home and 4 small files:

export GOG_HOME="$(mktemp -d)"
cd "$(mktemp -d)"
printf 'Hello,\n\nThe agenda for Monday is attached.\n' > note.txt
printf '<p>Hello,</p>\n<p>The agenda for Monday is attached.</p>\n' > note.html
printf 'Agenda\n1. Budget review\n2. Hiring plan\n' > agenda.txt
printf 'Thanks, all. I will bring the figures.\n' > reply.txt

MESSAGE_ID, THREAD_ID and DRAFT_ID stand for the identifiers that Reading Gmail and the draft commands print. Output, Schemas and Dry Runs explains the structure of a dry-run plan.

Why drafts come first

A draft is a saved, unsent message in the Drafts folder of the account. It can be opened, corrected and sent from Gmail on the web or on a phone, and deleting it affects no one but you. A send command delivers the message before it returns.

Confirmation requirements vary by command.

CommandAsks for confirmationEffect
gog gmail sendnodelivers the message at once
gog gmail drafts send DRAFT_IDnodelivers the draft at once
gog gmail trash MESSAGE_IDnomoves the message to the trash
gog gmail drafts delete DRAFT_IDyes, or --forcedeletes the draft permanently; drafts do not go to the trash
gog calendar deleteyes, or --forcesee Google Calendar

A send has no prompt to stop it, so the review must happen before the command runs (internal/cmd/confirm.go). Have the script or agent create a draft for review in Gmail.

Once you approve it, send it with the Send button or gog gmail drafts send. The --gmail-no-send flag allows draft commands and blocks every send command (see the last section and Safety Controls for Scripts and Agents).

Message bodies

All composing commands take the body from the same family of flags:

FlagBody
--body TEXTplain text from the command line
--body-file PATHplain text from a file; - reads standard input
--body-html HTMLan HTML part sent alongside the plain-text part
--body-html-file PATHHTML from a file; - reads standard input
--html-from-textbuilds an HTML part from the plain body

With only a plain body, gog sends text/plain. Gmail on the web displays such a message with a hard line break about every 70 characters.

--html-from-text (or GOG_GMAIL_HTML_FROM_TEXT=1) adds an HTML alternative built from the same text, which Gmail reflows to the window (docs/gmail-workflows.md). An explicit --body-html takes precedence over it.

Prefer --body-file for anything longer than a sentence: the text keeps its line breaks, the shell does not interpret quotes or $ signs inside it, and a dry run checks that the file exists. To send attachments without any text, pass an explicitly empty body, --body ''.

The signature that Gmail adds in the web interface is not added to messages created through the API. --signature appends the Gmail signature of the sending address, --signature-from ADDRESS the signature of another send-as alias (an additional sending address that Gmail has verified for the account), and --signature-file PATH a local file.

Drafts

Creating a draft

gog gmail drafts create takes the same recipient, subject, body and attachment flags as a send. --subject is required, and --attach can be repeated:

$ gog --account you@example.com --dry-run --json gmail drafts create --to friend@example.com --subject "Agenda for Monday" --body-file note.txt --attach agenda.txt
{
  "dry_run": true,
  "op": "gmail.drafts.create",
  "request": {
    "attachments": [
      "agenda.txt"
    ],
    "auto_from_addressed_alias": false,
    "bcc": null,
    "body_html_len": 0,
    "body_len": 43,
    "cc": null,
    "from": "",
    "quote": false,
    "reply_all": false,
    "reply_to": "",
    "reply_to_message_id": "",
    "signature": false,
    "signature_file": "",
    "signature_from": "",
    "subject": "Agenda for Monday",
    "thread_id": "",
    "to": [
      "friend@example.com"
    ]
  }
}

Without --dry-run, the JSON result of every draft-writing command has the keys draftId, message (the Gmail message inside the draft), threadId, inReplyTo, references and replyContextSource, plus attachments with filename and size in bytes when the draft has files (internal/cmd/gmail_drafts.go). Keep draftId to identify the draft in later commands.

Listing and reading drafts

gog --account you@example.com gmail drafts list
gog --account you@example.com gmail drafts list --all --json --results-only
gog --account you@example.com gmail drafts get DRAFT_ID
gog --account you@example.com gmail drafts get DRAFT_ID --format raw --plain > stored.eml
gog --account you@example.com gmail drafts get DRAFT_ID --download

drafts list returns 20 drafts per page by default and has the same --max, --page, --all and --fail-empty flags as the searches. Each item has id (the draft ID), messageId and threadId. drafts get --format raw prints the stored message, which lets you check the exact bytes before anyone sends it, and --download saves the draft’s attachments.

Updating a draft

gog gmail drafts update DRAFT_ID rewrites the draft. It requires --subject on every call, even when only the body changes:

$ gog --account you@example.com --dry-run --json gmail drafts update DRAFT_ID --body "x"
required: --subject
{"error":{"class":"usage","code":2,"message":"required: --subject"}}

Updating a draft retains recipients and attachments unless you change them explicitly. The plan shows what gog will keep with the *_keep_existing and preserve_attachments fields:

$ gog --account you@example.com --dry-run --json gmail drafts update DRAFT_ID --cc you@example.org --body-file note.txt --subject "Agenda for Monday" | jq -c '.request | {to, to_keep_existing, cc, cc_keep_existing, bcc_keep_existing, preserve_attachments}'
{"to":null,"to_keep_existing":true,"cc":["you@example.org"],"cc_keep_existing":false,"bcc_keep_existing":true,"preserve_attachments":true}

Pass --cc '' or --bcc '' to clear a field. --attach replaces all attachments, --clear-attachments removes them, and --clear-reply-context turns a reply draft into a standalone message by dropping its reply headers.

Sending and deleting a draft

gog gmail drafts send DRAFT_ID sends the draft as it is stored, without a prompt:

$ gog --account you@example.com --dry-run --json gmail drafts send DRAFT_ID
{
  "dry_run": true,
  "op": "gmail.drafts.send",
  "request": {
    "draft_id": "DRAFT_ID"
  }
}

gog gmail drafts delete DRAFT_ID removes a draft permanently. It asks for confirmation, and in a non-interactive run it refuses unless you add --force:

$ gog --account you@example.com --no-input gmail drafts delete DRAFT_ID
refusing to permanently delete gmail draft DRAFT_ID (not recoverable; drafts are not moved to Trash) without --force (non-interactive)

Sending a new message

gog gmail send (also available as the top-level shortcut gog send) composes and sends in 1 step. --to, --cc and --bcc take comma-separated lists, --subject is required for a new message, and --attach can be repeated:

$ gog --account you@example.com --dry-run --json gmail send --to friend@example.com --cc you@example.org --bcc you@example.com --subject "Agenda for Monday" --body-file note.txt --body-html-file note.html --attach agenda.txt
{
  "dry_run": true,
  "op": "gmail.send",
  "request": {
    "attachments": [
      "agenda.txt"
    ],
    "bcc": [
      "you@example.com"
    ],
    "body_html_len": 56,
    "body_len": 43,
    "cc": [
      "you@example.org"
    ],
    "from": "",
    "reply_all": false,
    "reply_to": "",
    "reply_to_message_id": "",
    "signature": false,
    "signature_file": "",
    "signature_from": "",
    "subject": "Agenda for Monday",
    "thread_id": "",
    "to": [
      "friend@example.com"
    ],
    "track": false,
    "track_split": false
  }
}

The plan lists both body parts by length and the attachment by path. It does not open the attachment, so a missing file is reported only by the real send. Other useful flags are --from ADDRESS, which sends from a send-as alias, and --reply-to ADDRESS, which sets the Reply-To header.

After a real send, the JSON result is an object with messageId and threadId of the new message, from, and attachments with filename and size when files were attached. When --track-split sends a separate copy to each recipient, the result is {"messages": [...]} with 1 such object per copy, each with its to (internal/cmd/gmail_compose.go).

Replying

The Gmail API has no reply operation of its own: a client has to fetch the original message, address the answer, copy the threading headers and quote the text. gog gmail reply and gog gmail reply-all do that work for you.

$ gog --account you@example.com --dry-run --json gmail reply MESSAGE_ID --body "Thanks, Monday at 10:00 works for me." | jq -c '.request | {message_id, quote, to_add, remove, subject_override}'
{"message_id":"MESSAGE_ID","quote":true,"to_add":null,"remove":null,"subject_override":""}

Their defaults follow Gmail’s own composer (docs/gmail-workflows.md):

  • The subject is the original subject with 1 Re: prefix.
  • The original message is quoted below the reply; --no-quote leaves it out. The plan shows this as "quote": true.
  • reply answers the Reply-To address when the original has one, otherwise the sender.
  • reply-all also keeps the original To and Cc recipients, except your own account and its send-as aliases.

The recipient flags edit the list gog derives from the original message. --to, --cc and --bcc add an address, or move an inherited address into that field, and --remove deletes an address from every field.

All 4 can be repeated. --subject overrides the subject, but a changed subject makes Gmail start a new conversation.

Reply drafts

gog gmail drafts reply and gog gmail drafts reply-all build exactly the same message and save it as a draft:

$ gog --account you@example.com --dry-run --json gmail drafts reply-all MESSAGE_ID --body-file reply.txt --remove you@example.org --no-quote | jq -c '{op} + (.request | {message_id, quote, remove})'
{"op":"gmail.drafts.reply-all","message_id":"MESSAGE_ID","quote":false,"remove":["you@example.org"]}

A dry run of a reply does not fetch the original message, so it cannot tell you the final recipient list. To verify the recipients before sending, open the draft in Gmail or inspect it with gog gmail drafts get DRAFT_ID.

Replying to a thread

reply and reply-all take a message ID. When you only have a thread ID, use --thread-id on gmail send or gmail drafts create. gog then replies to the latest message of the thread. Add --reply-all to derive the recipients and --quote to include the quoted text, which is off by default on these commands:

$ gog --account you@example.com --dry-run --json gmail drafts create --thread-id THREAD_ID --reply-all --quote --body-file reply.txt | jq -c '.request | {thread_id, reply_all, quote, to, subject}'
{"thread_id":"THREAD_ID","reply_all":true,"quote":true,"to":null,"subject":""}

--to and --subject are not required here because gog derives them from the thread, and the subject receives the Re: prefix (internal/cmd/gmail_drafts.go). The documentation describes --reply-to-message-id on gmail send as the lower-level way to compose a reply: an explicit --to or --cc replaces the derived recipients, and you must request quoting. For typical replies, the documentation recommends gmail reply and gmail reply-all.

Forwarding

gog gmail forward MESSAGE_ID forwards a message with a Fwd: subject, a forwarded-message block and the original attachments. --note (or --note-file, --note-html, --note-html-file) adds your text above the forwarded message, and --skip-attachments leaves the files out. gog gmail drafts forward saves the same message as a draft, and there --to is optional (docs/gmail-workflows.md):

$ gog --account you@example.com --dry-run --json gmail drafts forward MESSAGE_ID --to you@example.org --note "Forwarding for your records."
{
  "dry_run": true,
  "op": "gmail.drafts.forward",
  "request": {
    "bcc": null,
    "cc": null,
    "from": "",
    "message_id": "MESSAGE_ID",
    "note_html_len": 0,
    "note_len": 28,
    "signature": false,
    "signature_file": "",
    "signature_from": "",
    "skip_attachments": false,
    "to": [
      "you@example.org"
    ]
  }
}

Labels, archive, read state and trash

Gmail organizes mail with labels. Archiving removes INBOX, and marking a message as read removes UNREAD. gog offers both general label commands and named shortcuts (internal/cmd/gmail_archive.go).

CommandActs onLabel change in the plan
gog gmail labels modify THREAD_ID ... --add L --remove L1 or more threadsas given
gog gmail thread modify THREAD_ID --add L --remove Lall messages of 1 threadas given
gog gmail messages modify MESSAGE_ID --add L --remove L1 messageas given
gog gmail archive MESSAGE_ID ... (or --thread THREAD_ID)messages, or whole threadsremoves INBOX
gog gmail mark-read MESSAGE_ID ...messagesremoves UNREAD
gog gmail unread MESSAGE_ID ...messagesadds UNREAD
gog gmail trash MESSAGE_ID ...messagesadds TRASH, removes INBOX

--add and --remove accept label names or IDs, comma-separated or repeated. thread modify also has --add-label and --remove-label for a label name that itself contains a comma. The plans show the label changes directly:

$ gog --account you@example.com --dry-run --json gmail labels modify THREAD_ID --add Receipts --remove INBOX
{
  "dry_run": true,
  "op": "gmail.labels.modify",
  "request": {
    "add": [
      "Receipts"
    ],
    "remove": [
      "INBOX"
    ],
    "thread_ids": [
      "THREAD_ID"
    ]
  }
}
$ gog --account you@example.com --dry-run --json gmail archive --thread THREAD_ID
{
  "dry_run": true,
  "op": "gmail.archive",
  "request": {
    "action": "archived",
    "removed_labels": [
      "INBOX"
    ],
    "resource": "thread",
    "thread_ids": [
      "THREAD_ID"
    ]
  }
}

archive, mark-read, unread and trash can also select messages by query with --query (-q). --max caps the number of messages, 100 by default. Preview a query-based change before you run it, because it can touch many messages at once:

$ gog --account you@example.com --dry-run --json gmail mark-read --query 'is:unread label:Newsletters' --max 200
{
  "dry_run": true,
  "op": "gmail.read",
  "request": {
    "action": "marked as read",
    "added_labels": [],
    "max": 200,
    "message_ids": [],
    "query": "is:unread label:Newsletters",
    "removed_labels": [
      "UNREAD"
    ]
  }
}

The plan of a query-based command shows only the query. To see which messages it would touch, run the same query with gog gmail messages search first.

The trash

gog gmail trash moves messages to the trash by adding the TRASH label; it does not delete them permanently. It runs without a confirmation prompt:

$ gog --account you@example.com --dry-run --json gmail trash MESSAGE_ID
{
  "dry_run": true,
  "op": "gmail.trash",
  "request": {
    "action": "trashed",
    "added_labels": [
      "TRASH"
    ],
    "max": 100,
    "message_ids": [
      "MESSAGE_ID"
    ],
    "query": "",
    "removed_labels": [
      "INBOX"
    ]
  }
}

Permanent deletion is a separate command, gog gmail batch delete, which asks for confirmation and needs the broader https://mail.google.com/ OAuth scope, the permission that the account granted to gog at sign-in (see Authentication and Accounts). For ordinary cleanup, the gog documentation recommends the trash, which leaves room to recover from a mistake in Gmail.

A draft-first workflow

The following script saves a reply as a draft and prints the command that would send it. It passes --gmail-no-send, so even a mistake in the script cannot send mail, and it checks the dry-run plan before it writes anything:

#!/usr/bin/env bash
# Usage: draft-reply.sh MESSAGE_ID BODY_FILE
set -euo pipefail

message_id=$1
body_file=$2
common=(--no-input --gmail-no-send --json)

gog "${common[@]}" --dry-run gmail drafts reply "$message_id" \
  --body-file "$body_file" | jq -e '.op == "gmail.drafts.reply"' >/dev/null

draft_id=$(gog "${common[@]}" gmail drafts reply "$message_id" \
  --body-file "$body_file" | jq -er '.draftId')

echo "saved draft $draft_id"
echo "read it in Gmail, then send it with: gog gmail drafts send $draft_id"
GOG_ACCOUNT=you@example.com ./draft-reply.sh MESSAGE_ID reply.txt

jq -er prints the raw value and fails when draftId is missing, so the script never reports a draft that does not exist. The send itself stays a separate, deliberate step for a person.

What --gmail-no-send blocks

--gmail-no-send (or GOG_GMAIL_NO_SEND=1) refuses every Gmail send operation (internal/cmd/gmail_no_send.go), and it does so even in a dry run, so the plan already tells you that the command would be blocked:

$ gog --account you@example.com --dry-run --json --gmail-no-send gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt
Gmail sending is blocked by --gmail-no-send
{"error":{"class":"usage","code":2,"message":"Gmail sending is blocked by --gmail-no-send"}}
$ gog --account you@example.com --dry-run --json --gmail-no-send gmail drafts send DRAFT_ID
Gmail sending is blocked by --gmail-no-send
{"error":{"class":"usage","code":2,"message":"Gmail sending is blocked by --gmail-no-send"}}

Creating a draft is still allowed:

$ gog --account you@example.com --dry-run --json --gmail-no-send gmail drafts create --to friend@example.com --subject "Agenda for Monday" --body-file note.txt | jq -c '{dry_run, op}'
{"dry_run":true,"op":"gmail.drafts.create"}

To persist the send block for an account, use gog config no-send set. Safety Controls for Scripts and Agents explains how to combine it with command allowlists and --readonly.

Google Calendar

Use gog to list calendars and events, read individual events, create events with attendees and reminders, update or delete events, respond to invitations, and check availability. The examples show how time zones affect date ranges, event times, and display.

Read commands need a signed-in account (see Authentication and Accounts). Their expected output is described using the gog v0.48.1 source.

Write commands are shown with their --dry-run --json plans, captured with an empty configuration. The examples use the zone America/Toronto and the placeholder EVENT_ID for an event identifier.

Calendar IDs

Every calendar command names a calendar by its calendar ID. Your main calendar is always available as primary. Other calendars have IDs in the form of an email address, and many commands also accept the calendar’s display name or its position in the output of gog calendar calendars.

gog --account you@example.com calendar calendars
gog --account you@example.com calendar calendars --json --results-only

gog calendar calendars lists the calendars on your calendar list, 100 per page by default, with --page, --all and --fail-empty as usual. The table has the columns ID, NAME and ROLE, where the role is your access level, such as owner or reader. The JSON is {"calendars": [...], "nextPageToken": ...}, and each item is a Calendar API calendar-list entry with fields such as id, summary (the name), timeZone and accessRole (internal/cmd/calendar_list_cmds.go).

Listing events

gog calendar events (aliases list and ls) lists the events of 1 calendar, primary by default. Without any range flag it covers the next 7 days, starting now (internal/cmd/time_helpers.go).

gog --account you@example.com calendar events
gog --account you@example.com calendar events --today
gog --account you@example.com calendar events --tomorrow --json
gog --account you@example.com calendar events --week --week-start sun
gog --account you@example.com calendar events --days 3
gog --account you@example.com calendar events --from 2026-12-01 --to 2026-12-04
gog --account you@example.com calendar events --from 2026-12-01T09:00:00-05:00 --to 2026-12-01T17:00:00-05:00
gog --account you@example.com calendar events --from monday --to "next friday"

Choosing the period

FlagsPeriod
nonefrom now for 7 days
--today, --tomorrowthat whole day
--weekthe current week; --week-start sun (or mon, the default) chooses the first day
--days NN whole days, starting today or at --from
--from X --to Yan explicit period; X and Y can be RFC 3339 times (date, time and UTC offset, such as 2026-12-01T09:00:00-05:00), dates or relative words
--from X alone7 days starting at X

--today, --tomorrow and --week each describe a complete period, so gog rejects 2 of them together, and it rejects their combination with --from, --to or --days. --days and --to both set the end of the period and cannot be combined either.

A date-only --to includes that whole day, so --from 2026-12-01 --to 2026-12-04 covers 4 days. A period whose end is not after its start is a usage error. The accepted time formats are listed in Output, Schemas and Dry Runs.

Time zones in a listing

gog uses time zones for 2 purposes when listing events.

  • Date-range time zone. gog asks Google for the time zone of your primary calendar and interprets --today, --week, dates, relative words and times without an offset in that zone, whatever the zone of the computer that runs the command (internal/cmd/time_helpers.go). An RFC 3339 value with an offset names an exact instant and needs no zone.
  • Display time zone. --timezone ZONE changes only how event times are printed. Without it, gog displays the event in its own time zone if available and otherwise uses its calendar’s time zone. --timezone local uses the zone of the computer.
gog --account you@example.com calendar events --week --timezone America/Toronto
gog --account you@example.com calendar events --week --timezone local

If “today” looks wrong, check the time zone of the primary calendar in the Google Calendar settings, because that setting decides where the day begins.

More than 1 calendar

gog --account you@example.com calendar events you@example.org --today
gog --account you@example.com calendar events --cal primary --cal "Team" --week --all-pages --sort start
gog --account you@example.com calendar events --all --today --sort start

A positional calendar ID selects 1 calendar. --cal can be repeated, and --calendars takes a comma-separated list of IDs, names or positions. --all reads every calendar on your list.

On gog calendar events, --all selects all calendars and --all-pages fetches all pages of results. On Gmail search commands, --all and --all-pages are aliases.

A page token belongs to 1 calendar, so use --all-pages when you read several calendars. With several calendars, --sort start gives chronological output.

Other listing flags

FlagEffect
--max Nevents per page, 10 by default
--query TEXTfree-text search within the period
--event-types T,...only some event types: default, birthday, focus-time, from-gmail, out-of-office, working-location
--sort start|end|summary|calendar, --order asc|descsort the output; without --sort the API order is kept
--weekday, --locationadd day-of-week or location columns to the table
--fields F,...a field mask: the event fields that the Calendar API itself should return (this command’s own meaning of --fields)
--fail-emptyexit with code 3 when there are no events
gog --account you@example.com calendar events --week --max 50 --weekday --location
gog --account you@example.com calendar events --week --query "review"
gog --account you@example.com calendar events --today --plain

gog calendar search QUERY is a separate command for text search. Its default period runs from 30 days before now to 90 days after now (docs/dates.md), it searches 1 calendar (--calendar, default primary), and it returns up to 25 events:

gog --account you@example.com calendar search "review" --days 14

Fields of the event list

The table has the columns ID, START, END and SUMMARY, with CALENDAR first when several calendars are listed and the optional START_DOW, END_DOW and LOCATION. The JSON is {"events": [...], "nextPageToken": ...} for 1 calendar; for several calendars the page tokens are in nextPageTokens, 1 per calendar (internal/cmd/calendar_list.go).

Each event is the Calendar API event resource, with fields such as id, summary, description, location, start, end, attendees, status and htmlLink. start and end contain either dateTime (with an offset) and timeZone, or date for an all-day event. gog adds fields that make scripts simpler (internal/cmd/calendar_event_days.go):

FieldMeaning
startLocal, endLocalstart and end in RFC 3339 in the display zone, or the date for an all-day event
startDayOfWeek, endDayOfWeekthe weekday names of start and end
timezonethe zone used for the local fields
eventTimezonethe event’s own zone, present only when it differs from timezone
calendarIdthe calendar of the event, in lists that cover several calendars (also repeated as CalendarID)

Reading an event

gog --account you@example.com calendar event primary EVENT_ID
gog --account you@example.com calendar event primary EVENT_ID --json --timezone America/Toronto
gog --account you@example.com calendar raw primary EVENT_ID

gog calendar event CALENDAR_ID EVENT_ID (aliases get, info, show) prints 1 event (internal/cmd/calendar_events_cmds.go). Its JSON is {"event": {...}} with the same fields as a list item. gog calendar raw prints the unprocessed API response.

Creating an event

gog calendar create CALENDAR_ID requires --summary (the title), --from and --to. The calendar ID is a required positional argument, so name primary explicitly (internal/cmd/calendar_edit.go):

$ gog --account you@example.com --dry-run --json calendar create --summary "Review" --from "2026-05-06T10:00:00+02:00" --to "2026-05-06T10:30:00+02:00"
expected "<calendarId>"
{"error":{"class":"usage","code":2,"message":"expected \"\u003ccalendarId\u003e\""}}

A complete timed event with an attendee, a location and a description:

$ gog --account you@example.com --dry-run --json calendar create primary --summary "Project review" --from 2026-12-03T14:00:00-05:00 --to 2026-12-03T15:00:00-05:00 --timezone America/Toronto --attendees friend@example.com --location "Room 4B" --description "Review the open items before the holidays."
{
  "dry_run": true,
  "op": "calendar.create",
  "request": {
    "calendar_id": "primary",
    "conference_version_1": false,
    "event": {
      "attendees": [
        {
          "email": "friend@example.com"
        }
      ],
      "description": "Review the open items before the holidays.",
      "end": {
        "dateTime": "2026-12-03T15:00:00-05:00",
        "timeZone": "America/Toronto"
      },
      "location": "Room 4B",
      "start": {
        "dateTime": "2026-12-03T14:00:00-05:00",
        "timeZone": "America/Toronto"
      },
      "summary": "Project review"
    },
    "send_updates": "",
    "supports_attachments": false
  }
}

The event object is the resource gog will send to the Calendar API. A successful creation prints the new event in the same form as gog calendar event.

Times and time zones when creating

The --from and --to flags for calendar create expect RFC 3339 values. gog copies the text into start.dateTime and end.dateTime unchanged, so relative words such as tomorrow are not converted (see Output, Schemas and Dry Runs). Always include the offset.

The IANA time zone name, such as America/Toronto, is the name of a region’s rules, including daylight saving time; an offset such as -05:00 is only the difference from UTC at 1 moment. --timezone ZONE sets the name on both start and end, and --start-timezone and --end-timezone set them separately; the 2 forms cannot be combined. Without any of them, gog derives a fixed-offset zone from the offset in the time:

$ gog --account you@example.com --dry-run --json calendar create primary --summary "Project review" --from 2026-12-03T14:00:00-05:00 --to 2026-12-03T15:00:00-05:00 | jq '.request.event.start'
{
  "dateTime": "2026-12-03T14:00:00-05:00",
  "timeZone": "Etc/GMT+5"
}

Etc/GMT+5 is a fixed offset of UTC minus 5 hours without any daylight saving rules (the sign in these names is reversed by convention). Pass --timezone America/Toronto so that the event carries the rules of the region in which it takes place. An unknown time zone name causes exit code 2, even in a dry run.

All-day events

--all-day takes dates without a time in --from and --to. gog copies them into start.date and end.date:

$ gog --account you@example.com --dry-run --json calendar create primary --summary "Team offsite" --from 2026-12-10 --to 2026-12-11 --all-day | jq '.request.event'
{
  "end": {
    "date": "2026-12-11"
  },
  "start": {
    "date": "2026-12-10"
  },
  "summary": "Team offsite"
}

An all-day event has no time zone, so gog refuses --timezone with --all-day:

$ gog --account you@example.com --dry-run --json calendar create primary --summary "Team offsite" --from 2026-12-10 --to 2026-12-11 --all-day --timezone America/Toronto
--timezone cannot be used with all-day dates
{"error":{"class":"usage","code":2,"message":"--timezone cannot be used with all-day dates"}}

Attendees, reminders and notifications

--attendees takes a comma-separated list of addresses. A suffix after a semicolon changes 1 attendee: ;optional marks an optional guest, ;resource a room or other resource, and ;comment=TEXT adds a note. --reminder METHOD:DURATION (for example popup:10m or email:1d) replaces the calendar’s default reminders, up to 5 times, and --no-reminders turns reminders off.

$ gog --account you@example.com --dry-run --json calendar create primary --summary "Design sync" --from 2026-12-08T10:00:00-05:00 --to 2026-12-08T10:30:00-05:00 --timezone America/Toronto --attendees "friend@example.com,you@example.org;optional" --reminder popup:10m --send-updates all | jq '.request | {send_updates, attendees: .event.attendees, reminders: .event.reminders}'
{
  "send_updates": "all",
  "attendees": [
    {
      "email": "friend@example.com"
    },
    {
      "email": "you@example.org",
      "optional": true
    }
  ],
  "reminders": {
    "overrides": [
      {
        "method": "popup",
        "minutes": 10
      }
    ],
    "useDefault": false
  }
}

--send-updates decides whether Google emails the guests. Its values are all, externalOnly and none, and the default is none. A create, update or delete without the flag therefore changes the calendar without notifying the guests; pass --send-updates all when they should receive an invitation or a notice. Other values are rejected in the dry run.

Other creation flags include --rrule for recurrence (for example --rrule "RRULE:FREQ=WEEKLY;BYDAY=MO", copied into the event’s recurrence list), --with-meet to add a Google Meet link, --visibility, --transparency busy|free and --event-color. With --with-meet the plan contains a random requestId, so 2 dry runs of the same command differ in that field.

Updating an event

gog calendar update CALENDAR_ID EVENT_ID changes only the fields you name; everything else stays as it is (docs/examples.md). The plan shows this as a patch object. For the time zone, update has --start-timezone and --end-timezone but no --timezone flag:

$ gog --account you@example.com --dry-run --json calendar update primary EVENT_ID --from 2026-12-03T15:00:00-05:00 --to 2026-12-03T16:00:00-05:00 --start-timezone America/Toronto --end-timezone America/Toronto --add-attendee you@example.org
{
  "dry_run": true,
  "op": "calendar.update",
  "request": {
    "add_attendee": "you@example.org",
    "calendar_id": "primary",
    "conference_version_1": false,
    "event_id": "EVENT_ID",
    "original_start_time": "",
    "patch": {
      "end": {
        "dateTime": "2026-12-03T16:00:00-05:00",
        "timeZone": "America/Toronto"
      },
      "start": {
        "dateTime": "2026-12-03T15:00:00-05:00",
        "timeZone": "America/Toronto"
      }
    },
    "scope": "all",
    "send_updates": "",
    "supports_attachments": false,
    "wants_add_attendee": true
  }
}

Use --add-attendee to add guests to the existing list. --attendees replaces the whole list, and --attendees '' removes every guest. Likewise, an empty --summary, --description or --location clears that field:

$ gog --account you@example.com --dry-run --json calendar update primary EVENT_ID --location "" --description ""
{
  "dry_run": true,
  "op": "calendar.update",
  "request": {
    "add_attendee": "",
    "calendar_id": "primary",
    "conference_version_1": false,
    "event_id": "EVENT_ID",
    "original_start_time": "",
    "patch": {
      "description": "",
      "location": ""
    },
    "scope": "all",
    "send_updates": "",
    "supports_attachments": false,
    "wants_add_attendee": false
  }
}

For a recurring event, a series created with --rrule, --scope chooses what to change: all (the default) changes the whole series, single 1 occurrence, and future that occurrence and the ones after it. single and future also need --original-start, the original start time of the occurrence.

Deleting an event

gog calendar delete CALENDAR_ID EVENT_ID takes the same --scope, --original-start and --send-updates flags as update:

$ gog --account you@example.com --dry-run --json calendar delete primary EVENT_ID --send-updates all
{
  "dry_run": true,
  "op": "calendar.delete",
  "request": {
    "calendar_id": "primary",
    "event_id": "EVENT_ID",
    "original_start": "",
    "scope": "all",
    "send_updates": "all"
  }
}

It asks for confirmation. In a non-interactive run it refuses with exit code 2 unless you pass --force (internal/cmd/confirm.go):

$ gog --account you@example.com --no-input calendar delete primary EVENT_ID
refusing to delete event EVENT_ID from calendar primary without --force (non-interactive)

Responding to invitations

gog calendar respond CALENDAR_ID EVENT_ID (aliases rsvp and reply) sets your answer to an invitation. --status takes accepted, declined, tentative or needsAction, and --comment adds a note to your response. Any other status is rejected in the dry run (internal/cmd/calendar_respond.go):

$ gog --account you@example.com --dry-run --json calendar respond primary EVENT_ID --status declined --comment "I am travelling that week."
{
  "dry_run": true,
  "op": "calendar.respond",
  "request": {
    "calendar_id": "primary",
    "comment": "I am travelling that week.",
    "event_id": "EVENT_ID",
    "status": "declined"
  }
}

Proposing a new time is a feature of the Google Calendar web interface only. gog calendar propose-time therefore prints a link that opens the proposal page in a browser.

Checking availability with free/busy data

gog calendar freebusy asks Google which periods are busy on 1 or more calendars and returns only those periods. It takes calendar IDs as a comma-separated argument or with repeated --cal, or --all for every calendar on your list, and the same --from and --to as calendar events:

gog --account you@example.com calendar freebusy you@example.com,you@example.org --from 2026-12-03T09:00:00-05:00 --to 2026-12-03T17:00:00-05:00
gog --account you@example.com calendar freebusy --cal primary --from today --to tomorrow --json

The table has the columns CALENDAR, START and END, 1 row per busy period. The JSON is {"calendars": {...}}, the free/busy map of the Calendar API: 1 key per calendar ID, each with a busy list of periods that have start and end (internal/cmd/calendar_freebusy.go). gog calendar conflicts uses the same data to report overlaps between busy periods across your calendars.

Scripts

The first script prints today’s events from all your calendars in time order, as tab-separated lines. It passes --readonly to block mutating requests.

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

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

events=$(gog --account "$account" --no-input --readonly --json \
  calendar events --all --today --all-pages --sort start --results-only)

printf '%s\n' "$events" |
  jq -r '.[] | [.startLocal, .endLocal, .calendarId, (.summary // "(no title)")] | @tsv'

--results-only picks the events list out of the wrapping object, and startLocal already holds either an RFC 3339 time or, for an all-day event, the date, so the script needs no special case.

The second script checks a proposed slot against your free/busy data and, if the slot is free, prints the event that gog would send to Google. Review the dry-run plan before creating the event.

#!/usr/bin/env bash
# Usage: propose-slot.sh START END TITLE
set -euo pipefail

start=$1
end=$2
title=$3
common=(--account you@example.com --no-input --json)

freebusy=$(gog "${common[@]}" --readonly calendar freebusy you@example.com \
  --from "$start" --to "$end")
busy=$(printf '%s\n' "$freebusy" | jq '[.calendars[]?.busy[]?] | length')

if [ "$busy" -gt 0 ]; then
  echo "the slot overlaps $busy busy period(s); pick another time" >&2
  exit 1
fi

gog "${common[@]}" --dry-run calendar create primary --summary "$title" \
  --from "$start" --to "$end" --timezone America/Toronto |
  jq '.request.event'
./propose-slot.sh 2026-12-03T14:00:00-05:00 2026-12-03T15:00:00-05:00 "Project review"

The script passes the RFC 3339 values unchanged to both commands. That matters: freebusy would also accept tomorrow, but create would forward the word as it is.

Safety Controls for Scripts and Agents

A script or an AI agent that holds your Google token can do anything the token allows, including sending mail in your name. gog checks commands and requests at several points before they reach Google.

Use this chapter to choose an OAuth grant, block sending at 3 levels, restrict available commands, and compile restrictions into a binary. The agent setup at the end allows reading and drafting while blocking sending.

Every refusal message and exit code in this chapter was captured from gog v0.48.1 in a throwaway home directory (GOG_HOME=$(mktemp -d)) with no Google account signed in. The one exception is exit code 6 for a missing scope, which needs a real token; it comes from the way gog maps an HTTP 403 response in internal/cmd/exit_codes.go.

The checks at a glance

When gog parses a command, it runs a fixed series of checks before any data leaves your machine, and Google adds a final check of its own. The order matters: an earlier check stops the command before a later one is consulted, so the first refusal you see is not necessarily the only one that would apply. The order below follows the run function in internal/cmd/root.go.

Figure 8.1. A command meets the baked profile, the command lists and the send guard before its handler runs; a dry run ends inside the handler; the read-only guard inspects each HTTP request; Google finally checks the OAuth scopes of the token.

CheckSet byWho can change itRefusal exit code
Baked safety profilebuild-safe.sh at build timeonly a rebuild2
Command lists--enable-commands, --enable-commands-exact, --disable-commands or their environment variablesthe caller, on every run2
Gmail send guard--gmail-no-send, GOG_GMAIL_NO_SEND, config key gmail_no_send, gog config no-send setthe caller for the flag; for the config entries, whoever can edit config.json or point gog at another config directory2
Runtime read-only guard--readonly, GOG_READONLYthe caller, on every run2
OAuth scopesgog auth addonly a new authorization6 (from Google)

An OAuth scope is a named permission that you approve on Google’s consent screen. It is written as a URL such as https://www.googleapis.com/auth/gmail.readonly. Google limits the actions a token can authorize to its granted scopes.

OAuth scopes chosen at gog auth add

Scopes are the only check that Google enforces, so they are the one control that still holds if a caller swaps the gog binary or edits its configuration. You choose them when you authorize an account, and the stored refresh token carries exactly that grant. A refresh token is the long-lived credential that gog exchanges for short-lived access tokens; gog keeps it in its keyring, which is either the operating system’s secure credential store or an encrypted file. Authentication and Accounts covers the sign-in flow; this section concentrates on the flags that narrow the grant.

The scopes are decided by 3 flags of gog auth add:

  • --services selects which Google services to authorize, for example gmail,calendar. The default value user means all default user services, which is far more than a mail script needs.
  • --gmail-scope selects the Gmail grant: full, readonly, send or read-send.
  • The root flag --readonly asks for the read-only variant of every selected service that has one.

gog auth add accepts --dry-run, which prints the exact scopes it would request without opening a browser. That makes it a reliable way to compare grants offline:

$ gog --dry-run --json --readonly auth add you@example.com --services gmail,calendar --no-input | jq '.request.scopes'
[
  "email",
  "https://www.googleapis.com/auth/calendar.readonly",
  "https://www.googleapis.com/auth/gmail.readonly",
  "https://www.googleapis.com/auth/userinfo.email",
  "openid"
]

Without --readonly, the same command requests calendar, gmail.modify, gmail.settings.basic and gmail.settings.sharing. The 4 Gmail modes request the following Gmail scopes (captured the same way, with --services gmail):

--gmail-scopeGmail scopes requestedSuits
full (default)gmail.modify, gmail.settings.basic, gmail.settings.sharingreading, labels, drafts and sending
readonlygmail.readonlyreading only
sendgmail.sendsending only
read-sendgmail.readonly, gmail.sendreading and sending, but no drafts

The gog documentation implies 2 limits. First, a gmail.readonly grant cannot create drafts: docs/gmail-workflows.md states that draft writes need gmail.compose, gmail.modify or https://mail.google.com/, and a token with only gmail.send cannot write drafts either.

Second, gog offers no Gmail scope mode that allows drafts while excluding sending, so a job that must draft but never send has to rely on gog’s own guards for the send block. You can add individual scope URLs with --extra-scopes, but how Google treats each extra scope is outside what gog documents.

Tokens are stored per OAuth client name, so one account can hold a narrow token and a broad token side by side. An OAuth client is the client ID and secret, downloaded from the Google Cloud console as a JSON file, that identify gog to Google during sign-in. The client name is the label you pass with --client (or GOG_CLIENT); it selects both a credentials file and a separate token bucket, as described in docs/auth-clients.md:

gog --client reader auth credentials ~/Downloads/client_secret.json
gog --client reader --readonly auth add you@example.com --services gmail,calendar

Every later command that passes --client reader uses the read-only token. The recommended agent setup at the end of this chapter builds on this.

The runtime read-only guard

The root flag --readonly (or GOG_READONLY=1) has a second job besides narrowing auth add. On every other command it inspects each HTTP request just before gog sends it and rejects mutating requests; GET, HEAD, OPTIONS and a small allowlist of query endpoints that Google implements as POST still pass (docs/automation.md). The guard checks the HTTP request regardless of its OAuth scopes or the command that generated it.

The guard checks requests at the HTTP layer after gog loads credentials. In a home with no credentials, --readonly gmail send therefore fails earlier, with the missing-credentials error and exit code 10. To capture the guard’s own message, the run below passes a dummy direct access token (--access-token), which lets gog reach the dispatch step:

$ gog --account you@example.com --access-token fake-token --readonly gmail send --to friend@example.com --subject t --body b
Note: Using direct access token (expires in ~1 hour; no auto-refresh)
Post "https://gmail.googleapis.com/gmail/v1/users/me/messages/send?alt=json&prettyPrint=false": request blocked by --readonly: POST /gmail/v1/users/me/messages/send
$ echo $?
2

Dry runs and raw-message drafts reach different checks.

  • --dry-run ends a command inside its handler, before any request is built, so gog --readonly --dry-run gmail send ... prints its plan and exits 0. A dry run stops before testing the read-only guard.
  • Raw-message drafts (gmail drafts create --raw-file) are refused earlier, before authentication, with request blocked by --readonly: Gmail draft mutations are disabled and exit code 2.

The Gmail send guard

The send guard blocks every gog command that can deliver mail. It recognizes these command paths, listed in internal/cmd/gmail_no_send.go: the root shortcut send, gmail send, gmail reply, gmail reply-all, gmail forward, gmail autoreply and gmail drafts send. Draft commands such as gmail drafts create, gmail drafts reply and gmail drafts forward remain available.

You can switch the guard on in 4 places:

WhereHowScope
Flag--gmail-no-sendone run
EnvironmentGOG_GMAIL_NO_SEND=1every run in that environment
Config keygog config set gmail_no_send trueevery run that reads this config.json
Per accountgog config no-send set you@example.comevery run for that account

The guard runs before the command handler, so it holds under --dry-run as well:

$ gog --account you@example.com --gmail-no-send gmail send --to friend@example.com --subject t --body b
Gmail sending is blocked by --gmail-no-send
$ echo $?
2
$ gog --account you@example.com --gmail-no-send --dry-run gmail send --to friend@example.com --subject t --body b
Gmail sending is blocked by --gmail-no-send
$ echo $?
2

With --json, the same refusal also appears on standard output as an error object whose class is usage:

{"error":{"class":"usage","code":2,"message":"Gmail sending is blocked by --gmail-no-send"}}

The config entries name their source in the message:

$ gog config no-send set you@example.com
No-send enabled for you@example.com
$ gog --account you@example.com gmail send --to friend@example.com --subject t --body b
Gmail sending is blocked for you@example.com (config no-send)
$ gog config set gmail_no_send true
Set gmail_no_send = true
$ gog --account you@example.org gmail send --to friend@example.com --subject t --body b
Gmail sending is blocked by config gmail_no_send

These runs show 2 behaviors that matter in practice:

  • The flag cannot cancel a config entry. gog --gmail-no-send=false --account you@example.org gmail send ... still fails with Gmail sending is blocked by config gmail_no_send, because the flag can only add the guard. The entries live in one file, though: a caller that sets GOG_CONFIG_DIR or GOG_HOME, or passes --home, to another directory runs without them, and the same dry-run send then exits 0. With GOG_CONFIG_DIR alone, the tokens in the data directory stay usable. Config entries therefore guard against mistakes in commands; against a caller that controls its own environment, only a baked profile and the token’s scopes hold.
  • Register per-account guards under the email address. An account alias is a short name for an address, set with gog auth alias set. In v0.48.1, gog config no-send set work with the alias work for you@example.org is accepted and listed, yet a later gog --account work --dry-run gmail send ... is not blocked. The same guard stored as you@example.org blocks the account whether you select it by alias or by address.

Command allowlists and denylists

The command lists decide which gog commands may run at all. They use dot paths, so gmail.drafts.create names the command gmail drafts create.

FlagEnvironment variableMeaning
--enable-commandsGOG_ENABLE_COMMANDSallow these commands and everything below them (prefix match)
--enable-commands-exactGOG_ENABLE_COMMANDS_EXACTallow exactly these commands; a parent does not enable its children
--disable-commandsGOG_DISABLE_COMMANDSblock these commands and everything below them

If either allowlist is set, a command must match one of them; the denylist is applied afterward. The refusals look like this (internal/cmd/enabled_commands.go):

$ gog --account you@example.com --enable-commands-exact gmail.search gmail send --to friend@example.com --subject t --body b
command "gmail send" is not enabled (set --enable-commands or --enable-commands-exact to allow it)
$ echo $?
2
$ gog --account you@example.com --disable-commands gmail.send gmail send --to friend@example.com --subject t --body b
command "gmail send" is disabled (blocked by --disable-commands)
$ echo $?
2

gog matches the parsed command path. These 3 examples were verified with --dry-run.

  1. --disable-commands gmail.send does not block the root shortcut send, nor gmail reply, gmail reply-all or gmail forward. All of these deliver mail and have their own paths.
  2. --enable-commands gmail.drafts is a prefix rule, so it admits gmail drafts send.
  3. --enable-commands-exact gmail admits only the bare gmail command; gmail send is still refused.

A denylist therefore has to anticipate every path that leads to the action you want to prevent, while an exact allowlist only has to name what the job needs. For unattended jobs, prefer --enable-commands-exact with leaf commands, and combine it with the send guard, which already knows all the send paths.

Safety profiles and baked builds

A caller can omit runtime flags. A safety profile is a YAML policy that build-safe.sh compiles into a dedicated gog binary. Flags, environment variables, and configuration files cannot relax that policy (docs/safety-profiles.md).

The source tree ships 3 presets in safety-profiles/:

ProfileAllowsBlocks
agent-safereading, searching, drafting, labels, archiving and other recoverable actions, plus schemasending, deleting, sharing changes, admin operations and auth writes
readonlyread, list, search and get commands, plus schemaevery mutation, including drafts and local config writes
fulleverythingnothing; useful only to test the build

A profile mirrors the command tree. true allows a path, false blocks it, an explicit block beats an allowed parent, and once a profile contains any allow rule, everything it does not mention is blocked. An excerpt of agent-safe.yaml:

name: agent-safe

gmail:
  search: true
  send: false
  drafts:
    list: true
    create: true
    reply: true
    send: false

A profile can also pin boolean flags under locked-flags, for example sanitize-content: true or no-input: true, so that an agent receives sanitized output whether or not it asks for it.

To build a binary, run the script from a checkout of the source at the release you use; it needs a Go toolchain:

./build-safe.sh safety-profiles/agent-safe.yaml -o bin/gog-agent-safe

The script validates the profile, generates a Go file with the rules, builds with the safety_profile tag, runs the result with --version and deletes the generated file. A binary built from v0.48.1 reports its version with a -safe suffix. Its refusals name the profile, and runtime flags cannot override them:

$ bin/gog-agent-safe --account you@example.com gmail send --to friend@example.com --subject t --body b
command "gmail send" is blocked by baked safety profile "agent-safe"
$ echo $?
2
$ bin/gog-agent-safe --account you@example.com --enable-commands gmail.send gmail send --to friend@example.com --subject t --body b
command "gmail send" is blocked by baked safety profile "agent-safe"
$ bin/gog-agent-safe --account you@example.com --dry-run gmail drafts send r123
command "gmail drafts send" is blocked by baked safety profile "agent-safe"
$ bin/gog-readonly --account you@example.com --dry-run gmail drafts create --to friend@example.com --subject t --body b
command "gmail drafts create" is blocked by baked safety profile "readonly"

The same agent-safe binary accepts --dry-run gmail drafts create ... and prints the plan with exit code 0. Asking it for help on a blocked command prints the block message instead of the help page, and gog schema on such a binary lists only the allowed commands.

How a baked profile differs from the runtime flags:

PropertyRuntime flags and configBaked profile
Where the policy livesthe command line, the environment or config.jsoninside the executable
Who can relax itanyone who runs gog or edits its configonly someone who rebuilds the binary
Effect on help and gog schemanoneblocked commands disappear from both
When it is checkedafter parsing, after the profilefirst, right after parsing
Costnonea Go build per profile and per release

A baked profile restricts commands in that binary. Use narrow scopes because any other program with access to the token can do everything Google allows under those scopes.

Checking the effective policy

gog schema prints gog’s machine-readable description of its commands, flags, exit codes and output formats, and it also reports the safety state of the invocation it is part of, under .automation.safety (docs/automation.md). Pass the same global flags that the real job uses:

$ gog --gmail-no-send --readonly --enable-commands-exact schema,gmail.search,gmail.drafts.create schema | jq '.automation.safety | {gmail_no_send, readonly, command_rules, baked_profile}'
{
  "gmail_no_send": true,
  "readonly": true,
  "command_rules": {
    "enabled_prefixes": [],
    "enabled_exact": [
      "gmail.drafts.create",
      "gmail.search",
      "schema"
    ],
    "disabled": []
  },
  "baked_profile": {
    "enabled": false
  }
}

On the agent-safe binary, baked_profile reads {"enabled": true, "name": "agent-safe"}. A preflight step in a script can assert these values with jq -e before it runs the real command, as Automation and Troubleshooting shows. The snapshot describes one invocation only; it does not prove that the token is valid or what its scopes are.

Giving gog to an AI agent

An agent can reach gog in 2 ways: by running the CLI through a shell tool, guided by an agent skill, or by calling typed tools through gog’s MCP server. Both paths retain the checks in Figure 8.1. The shell exposes the CLI, and the server exposes a fixed set of tools.

Agent skills

An agent skill is a short instruction file that teaches a coding agent which commands exist and how to use them. gog publishes a core skill, one skill per service and a few hand-written workflow skills, such as gog-inbox-triage (prioritize unread mail without sending), in its repository; docs/agent-skills.md gives the install command for clients that support the Agent Skills format:

npx skills add https://github.com/openclaw/gogcli --skill gog gog-gmail

A skill only describes commands. The agent still runs whatever binary and flags its shell provides, so pair skills with an environment that enforces the policy: a baked binary on the agent’s PATH, GOG_GMAIL_NO_SEND=1 and an exact command allowlist in its environment.

The MCP server

gog mcp runs a Model Context Protocol server over standard input and output. MCP is a protocol through which an agent client discovers and calls tools that a server describes with fixed argument schemas. gog’s server exposes a small set of typed tools, each mapped to one gog operation, and deliberately offers no tool that runs arbitrary gog commands (docs/mcp.md).

--list-tools lists the registered tools without starting the server, which makes it easy to verify a configuration offline. With no other options, only read tools are registered:

$ gog --account you@example.com mcp --list-tools | jq -r '.tools[].name'
gmail_search
gmail_get_message
gmail_get_thread
drive_search
drive_get
docs_get
sheets_read_range
calendar_events
gmail_list_drafts
gmail_get_draft
gmail_list_labels

These server flags control which tools are registered.

  • --allow-tool narrows the set to named tools or services, for example gmail or gmail_search,calendar_events.
  • --allow-write adds write tools that match --allow-tool. For Gmail these include gmail_create_draft, gmail_update_draft, label changes, archiving and trashing.
  • --allow-gmail-send also registers gmail_send_message and gmail_send_draft; --allow-gmail-delete registers permanent deletion.

The root safety flags apply as well. --readonly removes every write tool from the list, and the server passes --gmail-no-send and the command lists on to each child command it runs.

When --allow-gmail-send and --gmail-no-send are both present, the send tools stay listed, and a call to gmail_send_message returns exit_code 2 with Gmail sending is blocked by --gmail-no-send in stderr. Selecting only write tools without --allow-write registers nothing:

$ gog --account you@example.com mcp --allow-tool gmail_create_draft --list-tools
no MCP tools enabled
$ echo $?
2

Configuring an agent for reads and drafts

The aim is an agent that can read mail and calendars, prepare reply drafts, and has no path to sending. Because no Gmail scope mode allows drafts without sending, the setup splits the work across 2 tokens and adds gog’s guards on top:

  1. Reading uses a read-only token. Authorize a separate client name with --readonly, as shown earlier: gog --client reader --readonly auth add you@example.com --services gmail,calendar. Run every read with --client reader --readonly.
  2. Drafting uses the default token under guards. The default full Gmail grant can write drafts. Register a per-account guard with gog config no-send set you@example.com, run draft commands with --gmail-no-send, and restrict them with --enable-commands-exact gmail.drafts.create (add gmail.drafts.reply or gmail.drafts.update if the agent needs them).
  3. The agent’s binary cannot send. Give the agent a binary built from safety-profiles/agent-safe.yaml, so that a forgotten flag or a different config directory still meets the baked block.
  4. After reviewing a draft, send it in Gmail or run gog gmail drafts send from your own shell with the stock binary. Run the agent in an environment, such as a container or a separate user account, that contains the baked binary but not the stock one, since an agent with a shell can call any executable it can reach.

For an MCP client, the same policy becomes the server command line. Each MCP tool runs one gog child command (gmail_search runs gmail messages search, gmail_get_thread runs gmail thread get, calendar_events runs calendar events, and the draft tools run gmail drafts list and gmail drafts create), so an exact allowlist must name mcp itself plus those child commands. This configuration registers 5 tools, 1 of which writes, and keeps the send tools unregistered:

{
  "command": "gog",
  "args": [
    "--account", "you@example.com",
    "--gmail-no-send",
    "--enable-commands-exact", "mcp,gmail.messages.search,gmail.thread.get,gmail.drafts.list,gmail.drafts.create,calendar.events",
    "--no-input",
    "mcp",
    "--allow-write",
    "--allow-tool", "gmail_search,gmail_get_thread,gmail_list_drafts,gmail_create_draft,calendar_events"
  ]
}

Run the same command with --list-tools to see the registered tools. The server registers gmail_search, gmail_get_thread, calendar_events, and gmail_list_drafts as read, and gmail_create_draft as write. With the root flag --dry-run added, a gmail_create_draft call returns the dry-run plan with exit_code 0, which shows that the allowlist admits the child command.

The preset agent-safe profile does not list mcp, so a binary baked from it refuses to start the server with command "mcp" is not included in baked safety profile "agent-safe". To bake an MCP policy, copy agent-safe.yaml, add mcp: true and build your own binary.

The worked example in Worked Example and Glossary applies the same restrictions to a shell script.

Automation and Troubleshooting

The commands in the earlier chapters also work in scripts. This chapter shows how to run gog without a terminal, parse JSON with jq, handle exit codes, select accounts, schedule jobs with cron or systemd, and diagnose authentication failures.

You will build inbox-digest.sh, which lists unread threads from the last day in Markdown.

Outputs shown here were captured from gog v0.48.1 in a throwaway home (GOG_HOME=$(mktemp -d)) with no Google account signed in. Commands that need a signed-in account appear without output.

Authentication and Accounts defines the credentials and permissions used in this chapter.

An OAuth client is the client ID and secret, downloaded from the Google Cloud console as a JSON file, that identify gog to Google. An OAuth scope is a named permission, such as read-only Gmail access, that you approve when you authorize an account. A refresh token is the long-lived credential that gog stores for an account and exchanges for short-lived access tokens.

Running without a terminal

A scheduled job has no one to answer a prompt, so it must never wait for input. The root flag --no-input makes gog fail when it would otherwise prompt, and gog also fails on prompts whenever standard input is not a terminal (internal/cmd/root.go). Pass the flag explicitly to keep the same behavior when testing the job by hand.

These 3 habits keep unattended runs predictable:

  • Authorize interactively, run unattended. gog auth add opens a browser consent flow; in v0.48.1 it starts that flow even under --no-input and only gives up when the authorization times out. Run it once by hand, or install a refresh token non-interactively with gog auth import (see Authentication and Accounts).
  • Read data from standard output only. gog writes results to stdout and writes prompts, progress, warnings and diagnostics to stderr (docs/automation.md), so 2>>log keeps the data stream clean.
  • Set the safety flags explicitly. Read-only jobs should pass --readonly, and any job that touches Gmail should pass --gmail-no-send unless sending is its purpose. Safety Controls for Scripts and Agents explains both.

JSON output and jq

--json (or -j) prints 1 JSON document on stdout. --plain prints tab-separated text (docs/automation.md). Setting GOG_JSON=1 makes JSON the default for every command in that environment, and an explicit --plain still overrides it. See Output, Schemas and Dry Runs for format details.

List commands wrap their results in an envelope. For gog gmail search, the envelope holds a threads array, a nextPageToken, and 2 fields that gog adds to paged lists: count, the number of rows in this response, and has_more, which is true when nextPageToken is not empty. The total number of matches on the server is separate from these pagination fields.

Use these 2 flags to reshape the result.

  • --results-only drops the envelope and prints only the primary array.
  • --select keeps only the named fields, for example --results-only --select id.

When a command fails in JSON mode, gog still prints the human message on stderr, and it also prints an error object on stdout whose code equals the exit status and whose class names it:

$ gog --account you@example.com --json --no-input gmail search 'is:unread'
OAuth client credentials missing (OAuth client ID JSON).
Download from: https://console.cloud.google.com/apis/credentials (Create Credentials → OAuth client ID → Desktop app → Download JSON)
Then run: gog auth credentials <credentials.json> (expected at /tmp/tmp.CNJtqGbBZU/data/credentials.json)
{"error":{"class":"config","code":10,"message":"OAuth client credentials missing (OAuth client ID JSON).\nDownload from: https://console.cloud.google.com/apis/credentials (Create Credentials → OAuth client ID → Desktop app → Download JSON)\nThen run: gog auth credentials <credentials.json> (expected at /tmp/tmp.CNJtqGbBZU/data/credentials.json)"}}

A jq filter that expects .threads will therefore fail on an error object, so check the exit status before you parse.

Exit codes

gog maps failures to stable exit codes, defined in internal/cmd/exit_codes.go, and gog schema exposes the map for programs to read.

$ gog --json schema | jq -c '.automation.exit_codes'
{"auth_required":4,"cancelled":130,"config":10,"empty_results":3,"error":1,"not_found":5,"ok":0,"orphaned":11,"permission_denied":6,"rate_limited":7,"retryable":8,"usage":2}
CodeNameTypical cause in a mail or calendar job
0oksuccess
1erroranything gog does not classify, such as a local network failure
2usagea bad flag, or a refusal by a safety check
3empty_resultsno results, only when you pass --fail-empty
4auth_requiredno token for the account, or an expired or revoked token
5not_foundthe message, thread or event does not exist
6permission_deniedGoogle returned HTTP 403, for example because a scope is missing
7rate_limitedquota still exhausted after gog’s own retries
8retryablea server error or a timeout
10configno OAuth client configured on this machine
130cancelledinterrupted with Ctrl-C

Branch on the status and keep a generic fallback, since later releases may add codes:

if json="$(gog --no-input --json gmail search --max 20 -- 'is:unread newer_than:1d')"; then
  printf '%s\n' "$json" | jq '.count'
else
  rc=$?
  case "$rc" in
    4) printf 'token missing or expired; run gog auth add again\n' >&2 ;;
    7 | 8) printf 'temporary failure; the next run will retry\n' >&2 ;;
    10) printf 'gog has no OAuth client on this machine\n' >&2 ;;
    *) printf 'gog failed with exit code %s\n' "$rc" >&2 ;;
  esac
  exit "$rc"
fi

Choosing the account and the client

A script should not depend on whichever account happens to be the default. gog resolves the account from --account first, then from GOG_ACCOUNT, then from the stored default account (docs/quickstart.md). Setting GOG_ACCOUNT in the job’s environment therefore lets one script serve several accounts without changes.

An account alias is a short name that stands for an address, set with gog auth alias set. The OAuth client name, chosen with --client or GOG_CLIENT, selects which credentials file and which stored token gog uses, so the same account can have a read-only token under one client name and a broader one under another. The per-user config.json contains aliases, client mappings, and per-account send guards.

$ gog auth alias set me you@example.com
alias	me
email	you@example.com
$ gog auth alias set work you@example.org
alias	work
email	you@example.org
$ gog config no-send set you@example.org
No-send enabled for you@example.org
$ gog config set timezone America/Toronto
Set timezone = America/Toronto
$ cat "$(gog config path)"
{
  "default_timezone": "America/Toronto",
  "account_aliases": {
    "me": "you@example.com",
    "work": "you@example.org"
  },
  "no_send_accounts": {
    "you@example.org": true
  }
}

gog config keys lists the keys you can set with gog config set: timezone, keyring_backend, gmail_no_send, youtube_api_key and places_api_key. Mappings from accounts or domains to client names (account_clients, client_domains) are described in docs/auth-clients.md.

Project: inbox-digest.sh

The script prints unread threads from the last day as a Markdown list you can paste into a note or email to yourself. It searches with gog --json gmail search under --readonly, so even a mistake in the script cannot change the mailbox.

#!/usr/bin/env bash
set -euo pipefail

gog_bin="${GOG:-gog}"
query="${DIGEST_QUERY:-is:unread newer_than:1d}"
max="${DIGEST_MAX:-100}"

digest_filter='
  def md: gsub("(?<c>[\\\\`*_\\[\\]<>#])"; "\\\(.c)");
  def line:
    "- **\((.subject // "") | if . == "" then "(no subject)" else md end)**"
    + " from \((.from // "unknown sender") | md)"
    + (if .date then ", \(.date)" else "" end)
    + (if (.messageCount // 1) > 1 then " (\(.messageCount) messages)" else "" end);
  "## Unread threads (\(.threads | length))",
  "",
  (if (.threads | length) == 0 then "No unread threads." else (.threads[] | line) end),
  (if .has_more then "", "_More threads match; raise DIGEST_MAX to see them._" else empty end)
'

json="$("$gog_bin" --readonly --no-input --json gmail search --max "$max" -- "$query")"
printf '%s\n' "$json" | jq -r "$digest_filter"

The script handles query parsing, result limits, and failures as follows.

  • gmail search returns 10 threads unless told otherwise, so the script sets --max and prints a note when has_more reports that more threads match.
  • The query follows --, which ends flag parsing; everything after it is query text, even a term that starts with a dash.
  • The jq function md escapes characters that Markdown would interpret, such as * and [ in a subject line.
  • Most thread fields are omitted from the JSON when they are empty, so the filter supplies a default for each one.
  • GOG lets you point the script at another binary, such as a baked gog-agent-safe, and DIGEST_QUERY lets you reuse it for other searches.
  • If gog fails, the assignment to json fails, and set -e ends the script with gog’s own exit code. In a home without an OAuth client, for example, the script exits with 10.

Testing the filter without an account

Use this sample to test the jq filter without signing in. gog schema describes commands, flags, exit codes, and the safety state. The sample takes its result fields from the threadItem type in internal/cmd/gmail_thread_search_helpers.go for each thread and from addPagedAggregates in internal/cmd/paged_list_helpers.go for count and has_more.

The second thread has no subject, and the third contains only an ID. These entries test the filter’s defaults.

{
  "count": 3,
  "has_more": false,
  "nextPageToken": "",
  "threads": [
    {
      "id": "thread-a",
      "date": "2026-11-27 08:15",
      "internalDateIso": "2026-11-27T08:15:02-05:00",
      "from": "Friend <friend@example.com>",
      "subject": "Agenda for *Friday* [draft]",
      "labels": ["INBOX", "UNREAD"],
      "messageCount": 3
    },
    {
      "id": "thread-b",
      "date": "2026-11-26 19:40",
      "internalDateIso": "2026-11-26T19:40:11-05:00",
      "from": "friend@example.com",
      "labels": ["INBOX", "UNREAD"],
      "messageCount": 1
    },
    {
      "id": "thread-c"
    }
  ]
}

To run the whole script against the sample, point GOG at a stub that ignores its arguments and prints the file:

#!/usr/bin/env bash
cat "$FIXTURE"
$ GOG=./fake-gog FIXTURE=sample.json ./inbox-digest.sh
## Unread threads (3)

- **Agenda for \*Friday\* \[draft\]** from Friend \<friend@example.com\>, 2026-11-27 08:15 (3 messages)
- **(no subject)** from friend@example.com, 2026-11-26 19:40
- **(no subject)** from unknown sender

With {"count":0,"has_more":false,"nextPageToken":"","threads":[]} the script prints the heading ## Unread threads (0) followed by No unread threads., and with has_more set to true it appends the note about DIGEST_MAX. The script passes shellcheck without warnings.

Watching for new mail and calendar changes

gog’s polling guide, docs/polling.md, covers Drive changes and Docs comments only; drive changes poll and docs comments poll keep their cursor in a state file and can run a hook per event. For Gmail and Calendar you choose between 3 approaches:

ApproachCommandWhat it needs
Repeat a search on a schedulegog gmail search 'is:unread newer_than:1h'nothing beyond a token
Read the change history since a cursorgog gmail history --since <historyId>a stored history ID
Receive push notificationsgog gmail watch start, then gog gmail watch pull or gog gmail watch servea Google Cloud Pub/Sub topic and subscription

A Gmail history ID is a mailbox-wide counter that increases with every change. gog gmail history --since lists the IDs of messages added after the given history ID, and its JSON output carries the current historyId, which becomes the cursor for the next run.

To obtain a first cursor, read it from any message: the message object in gog gmail get <messageId> --json is Gmail’s message resource, which includes historyId. A cursor that Gmail no longer accepts has to be reset the same way; docs/watch.md recommends falling back to a normal message listing in that case.

#!/usr/bin/env bash
set -euo pipefail

state="${XDG_STATE_HOME:-$HOME/.local/state}/gog-new-mail/history-id"
since="$(cat "$state")"

json="$(gog --readonly --no-input --json gmail history --since "$since" --all)"
printf '%s\n' "$json" | jq -r '.messages[]?'
printf '%s\n' "$json" | jq -r '.historyId' >"$state.tmp"
mv "$state.tmp" "$state"

The script prints 1 message ID per line and advances the cursor only after a successful read. The push approach, described in the same Gmail watch guide, suits a long-running service more than a scheduled job, because it needs a Pub/Sub subscription and credentials that can consume it.

For Calendar, gog calendar changed lists the most recently changed events, including deletions. Its --since flag takes an RFC 3339 timestamp, a date or a Go duration such as 24h, and defaults to 30 days, as its generated page docs/commands/gog-calendar-changed.md shows. A daily job can run gog --readonly --json calendar changed --since 24h.

Rate limits and retries

gog retries rate-limited requests automatically. Per docs/automation.md, a request that receives HTTP 429, or HTTP 403 with the reason rateLimitExceeded or userRateLimitExceeded, is retried up to 6 times with exponential backoff and jitter, which spans just under 94.5 seconds in total.

A Retry-After header is honored for delays up to 60 seconds per retry. If the quota is still exhausted afterward, the command exits with 7 (rate_limited); server errors and timeouts exit with 8 (retryable).

A scheduled job therefore needs no retry loop of its own. Let the run fail with 7 or 8 and rely on the next scheduled run, which avoids piling extra requests onto a quota that is already exhausted.

Running from cron or a systemd timer

A scheduler starts the job with a minimal environment: no login shell, often a short PATH, and no desktop session for the system keyring. Set the job’s environment explicitly. The keyring is where gog stores tokens; on a machine without a desktop session, use the encrypted file backend and supply its password through the environment, as docs/install.md describes for headless agents.

Keep the variables in a file that only you can read (mode 0600), for example ~/.config/inbox-digest/env:

GOG=/usr/local/bin/gog
GOG_ACCOUNT=you@example.com
GOG_KEYRING_BACKEND=file
GOG_KEYRING_PASSWORD=replace-with-your-keyring-password

The digest script also calls jq, so add a PATH= line to the file if jq lives outside the scheduler’s default path.

A systemd user service and timer then run the digest on weekday mornings. Save the service as ~/.config/systemd/user/inbox-digest.service:

[Unit]
Description=Unread mail digest

[Service]
Type=oneshot
EnvironmentFile=%h/.config/inbox-digest/env
ExecStart=/bin/sh -c '%h/bin/inbox-digest.sh > %h/inbox-digest.md'

and the timer as ~/.config/systemd/user/inbox-digest.timer:

[Unit]
Description=Run the unread mail digest on weekday mornings

[Timer]
OnCalendar=Mon..Fri 07:00
Persistent=true

[Install]
WantedBy=timers.target

Activate the timer, then run the service once by hand through systemd, which tests the same environment the timer will use:

systemctl --user daemon-reload
systemctl --user enable --now inbox-digest.timer
systemctl --user start inbox-digest.service
journalctl --user -u inbox-digest.service -n 20

With cron, the same job is one line in crontab -e. The set -a makes the shell export every variable it reads from the file:

0 7 * * 1-5 set -a; . "$HOME/.config/inbox-digest/env"; "$HOME/bin/inbox-digest.sh" > "$HOME/inbox-digest.md" 2>> "$HOME/inbox-digest.log"

Test any change by running the job through the scheduler itself. A command that works in your terminal only proves that your terminal has the right environment.

Diagnosing failures with gog auth doctor

gog auth doctor checks the local pieces that authentication depends on: the config file, the keyring backend and its password, and the stored tokens. With --check it also exchanges each refresh token for an access token, which proves that Google still accepts it. In a fresh home it reports a warning:

$ gog auth doctor
ok	config.path	/tmp/tmp.CNJtqGbBZU/config/config.json (optional; not created)
ok	keyring.backend	auto (source: default)
ok	keyring.dir	/tmp/tmp.CNJtqGbBZU/data/keyring
ok	keyring.open	opened
warn	tokens	no OAuth tokens stored
hint	tokens	run `gog auth add <email>`
status	warn

gog auth doctor exits with code 0 whenever it produces a report, including one with errors. In scripts, check the overall status field. The following preflight continues only when the status is ok:

doctor_json="$(gog --no-input --json auth doctor --check)"
if ! printf '%s\n' "$doctor_json" | jq -e '.status == "ok"' >/dev/null; then
  printf 'gog auth doctor did not report ok; not running the job\n' >&2
  exit 4
fi

gog auth doctor validates OAuth refresh tokens only. To test a service account, Application Default Credentials, or a direct access token, make a short read request.

Common failures and fixes

SymptomExit codeCauseFix
OAuth client credentials missing (OAuth client ID JSON).10no OAuth client on this machine, or a different GOG_HOMEgog auth credentials <file.json>; check that the job sees the same GOG_HOME
No auth for gmail you@example.com.4no stored token for this account and clientgog auth add you@example.com --services ..., with the same --client the job uses
a refresh fails with invalid_grant4the token expired or was revokedreauthorize the same account and client, keeping its services and scope modes
a call fails with HTTP 403 after you started using a new service6the token lacks that service’s scopereauthorize with the complete service list
no TTY available for keyring file backend password prompt1file keyring without GOG_KEYRING_PASSWORD in the job’s environmentadd the variable to the environment file the scheduler loads
keyring connection timed out ... (D-Bus SecretService may be unresponsive)1the system keyring is unreachableswitch to the file backend, or raise GOG_KEYRING_OPEN_TIMEOUT

Missing credentials

gog needs the OAuth client file before it can use any token. The message names the path where it looked, which reveals a GOG_HOME or user mismatch at a glance.

Missing token

Captured with a valid client but no token:

$ gog --account you@example.com --no-input gmail search 'is:unread'
No auth for gmail you@example.com.

OAuth (browser flow):
  gog auth add you@example.com --services gmail

Workspace service account (domain-wide delegation):
  gog auth service-account set you@example.com --key <service-account.json>
$ echo $?
4

The suggested gog auth add command omits the client name. If the job runs with --client reader, run gog --client reader auth add ... instead, or the new token lands in the default bucket.

Expired or revoked token

When Google rejects a refresh with invalid_grant, ordinary commands exit with 4 and auth doctor --check reports the failed refresh. Before you reauthorize, run gog auth list --json and note the account’s client, services and scope modes, because a bare gog auth add --force-consent requests the default services (docs/quickstart.md). Tokens that expire every 7 days usually indicate that the OAuth app is still in Testing mode on Google’s side; the quickstart describes how to publish it.

Missing scope after adding a service

A token covers only the services it was granted. If a job that used to read mail now also lists events, but the token was granted for Gmail only, Google answers the calendar call with HTTP 403 and gog exits with 6 (permission_denied). Reauthorize with every service the account needs, for example gog auth add you@example.com --services gmail,calendar --force-consent, keeping --readonly or the client name if the original grant used them.

Locked or unreachable keyring

On a headless machine the file keyring cannot ask for its password, and the doctor says so directly:

$ GOG_KEYRING_BACKEND=file gog --no-input auth doctor
ok	config.path	/tmp/tmp.uc7dAWGAOK/config/config.json (optional; not created)
ok	keyring.backend	file (source: env)
ok	keyring.dir	/tmp/tmp.uc7dAWGAOK/data/keyring
error	keyring.password	file keyring selected but GOG_KEYRING_PASSWORD is not set in a non-interactive process
hint	keyring.password	set GOG_KEYRING_PASSWORD or switch to a system keyring
ok	keyring.open	opened
warn	tokens	no OAuth tokens stored
hint	tokens	run `gog auth add <email>`
status	error

A real command in the same situation fails with ... no TTY available for keyring file backend password prompt; set GOG_KEYRING_PASSWORD and exit code 1. On a desktop whose Secret Service does not respond, storing a secret fails instead with:

store OAuth client secret: store secret: set secret: keyring connection timed out after 10s while storing keyring item (D-Bus SecretService may be unresponsive); set GOG_KEYRING_OPEN_TIMEOUT to allow more time, or set GOG_KEYRING_BACKEND=file and GOG_KEYRING_PASSWORD=<password> to use encrypted file storage instead

docs/paths.md adds a related setting for containers and other headless Linux hosts: DBUS_SESSION_BUS_ADDRESS=disabled: stops the keyring library from trying to start a session bus, and GOG_KEYRING_BACKEND=auto then selects the file backend.

Worked Example and Glossary

Extend the digest from Automation and Troubleshooting into a morning brief that reads your calendar and mail and prepares reply drafts with sending blocked, followed by a glossary of the book’s key terms.

As in the rest of the book, every command shown was checked against the --help output of gog v0.48.1, and every output was captured from a real run in a throwaway home without a Google account. Commands that need a signed-in account appear without output.

Morning brief script

Requirements

Write a script named morning-brief.sh that prints a Markdown document with 3 sections and meets the following requirements.

  1. Events today: list today’s events from your primary calendar with start and end times, and mark all-day events as such.
  2. Unread threads: list unread threads from the last day, as in inbox-digest.sh, and report when the list is incomplete.
  3. Reply drafts: for every thread that matches a reply query (by default is:unread newer_than:1d label:needs-reply), create a reply draft from a plain-text template file, unless the thread already has a draft. Print one line per new draft.
  4. Sending is impossible: all reads run under a read-only token. The draft step runs under flags and configuration that refuse every send command, so that a bug in the script, or a person who edits it carelessly, cannot deliver mail.
  5. Dry runs: with BRIEF_DRY_RUN=1, the script performs all reads but only previews the drafts.
  6. Failure handling: stop with gog’s exit code if a call fails. The script must also pass shellcheck without warnings.

Preparing the tokens and guards

The project uses the split from the recommended agent setup in Safety Controls for Scripts and Agents: a read-only token under the client name reader and the default token for drafts. Run these steps once, interactively:

gog auth credentials ~/Downloads/client_secret.json
gog --client reader auth credentials ~/Downloads/client_secret.json
gog --client reader --readonly auth add you@example.com --services gmail,calendar
gog auth add you@example.com --services gmail,calendar
gog auth alias set me you@example.com
gog config no-send set you@example.com

Before opening a browser, you can preview the read-only grant with gog --client reader --dry-run --json --readonly auth add you@example.com --services gmail,calendar --no-input; it reports the client reader and the scopes calendar.readonly and gmail.readonly, besides email, openid and userinfo.email. Note that the per-account guard uses the email address: a guard registered under the alias me would not take effect, as the safety chapter shows.

Hints

  • Keep 2 flag arrays, one for reads and one for the draft step, and pass them with "${read_flags[@]}". Quoted array expansion preserves every flag and value as a separate argument.
  • gog calendar events primary --today --json returns an events array. Each event carries startLocal and endLocal: an RFC 3339 timestamp for timed events and a plain date for all-day events, as internal/cmd/calendar_print.go formats them. The other fields, such as summary and location, come from the Calendar API event.
  • gog gmail drafts list --all --json returns a drafts array whose items carry id, messageId and threadId (internal/cmd/gmail_drafts.go). Compare its thread IDs with the search results to skip threads that already have a draft.
  • gog gmail drafts create --thread-id <threadId> --reply-all --body-file <file> saves a reply draft in the thread: --thread-id takes the reply headers from the latest message in the thread, and --reply-all fills the recipients from that message. The subject may be omitted when --thread-id is given.
  • --enable-commands-exact refuses every command it does not name, so give the read array only the 3 read commands and the write array only gmail.drafts.create.
  • A real draft result carries draftId; a dry run prints an object with "dry_run": true instead.

Worked solution

#!/usr/bin/env bash
set -euo pipefail

gog_bin="${GOG:-gog}"
account="${BRIEF_ACCOUNT:-me}"
read_client="${BRIEF_READ_CLIENT:-reader}"
unread_query="${BRIEF_UNREAD_QUERY:-is:unread newer_than:1d}"
reply_query="${BRIEF_REPLY_QUERY:-is:unread newer_than:1d label:needs-reply}"
reply_body="${BRIEF_REPLY_BODY_FILE:?set BRIEF_REPLY_BODY_FILE to a plain-text reply template}"
max="${BRIEF_MAX:-100}"

read_flags=(
  --account "$account" --client "$read_client"
  --readonly --gmail-no-send --no-input --json
  --enable-commands-exact "gmail.search,gmail.drafts.list,calendar.events"
)
write_flags=(
  --account "$account"
  --gmail-no-send --no-input --json
  --enable-commands-exact gmail.drafts.create
)
if [[ "${BRIEF_DRY_RUN:-0}" == 1 ]]; then
  write_flags+=(--dry-run)
fi

events_filter='
  def md: gsub("(?<c>[\\\\`*_\\[\\]<>#])"; "\\\(.c)");
  def hhmm: if test("T") then .[11:16] else "(all day)" end;
  "## Events today (\(.events | length))",
  "",
  (if (.events | length) == 0 then "No events today." else
    (.events[]
      | "- \((.startLocal // "") | hhmm)"
        + (if (.startLocal // "") | test("T") then "-\((.endLocal // "") | hhmm)" else "" end)
        + " \((.summary // "(no title)") | md)"
        + (if .location then " (\(.location | md))" else "" end))
  end)
'

threads_filter='
  def md: gsub("(?<c>[\\\\`*_\\[\\]<>#])"; "\\\(.c)");
  "## Unread threads (\(.threads | length))",
  "",
  (if (.threads | length) == 0 then "No unread threads." else
    (.threads[]
      | "- **\((.subject // "") | if . == "" then "(no subject)" else md end)**"
        + " from \((.from // "unknown sender") | md)"
        + (if .date then ", \(.date)" else "" end))
  end),
  (if .has_more then "", "_More threads match; raise BRIEF_MAX._" else empty end)
'

printf '# Morning brief for %s\n\n' "$(date +%F)"

"$gog_bin" "${read_flags[@]}" calendar events primary --today --max "$max" |
  jq -r "$events_filter"
printf '\n'

"$gog_bin" "${read_flags[@]}" gmail search --max "$max" -- "$unread_query" |
  jq -r "$threads_filter"
printf '\n'

candidates="$("$gog_bin" "${read_flags[@]}" gmail search --max "$max" -- "$reply_query")"
drafts="$("$gog_bin" "${read_flags[@]}" gmail drafts list --all)"
mapfile -t thread_ids < <(
  jq -rn --argjson c "$candidates" --argjson d "$drafts" '
    ([$d.drafts[]?.threadId] | map(select(. != null))) as $drafted
    | $c.threads[].id
    | select(. as $id | $drafted | any(. == $id) | not)
  '
)

printf '## Reply drafts (%d new)\n\n' "${#thread_ids[@]}"
if ((${#thread_ids[@]} == 0)); then
  printf 'No threads need a new draft.\n'
fi
for id in "${thread_ids[@]}"; do
  result="$("$gog_bin" "${write_flags[@]}" gmail drafts create \
    --thread-id "$id" --reply-all --body-file "$reply_body")"
  printf -- '- thread %s: %s\n' "$id" \
    "$(jq -r 'if .dry_run then "dry run, nothing created" else "draft \(.draftId)" end' <<<"$result")"
done

Run it with a template, first as a dry run:

printf 'Thanks for your message. I will reply in detail later today.\n' > ~/reply.txt
BRIEF_REPLY_BODY_FILE=~/reply.txt BRIEF_DRY_RUN=1 ./morning-brief.sh

How the solution meets each requirement:

  • Read-only access: every read passes --client reader --readonly, so the token is limited by Google to reading, and gog also refuses any mutating request.
  • Sending restrictions: the draft step allows exactly 1 command, gmail drafts create, adds --gmail-no-send, and runs for an account that carries a config guard. Each of the 3 would refuse a send on its own. For a stricter setup, set GOG to a binary baked from the agent-safe profile, which blocks every send command at build time.
  • No duplicate drafts: threads that already appear in the draft list are skipped, so running the script twice in one morning creates no second draft.
  • Failure handling: set -euo pipefail stops the script at the first failing gog call, including calls inside a pipeline, and the script exits with that call’s code.

The jq filters were checked against handwritten samples built from the definitions in the source, in the way the automation chapter tests inbox-digest.sh.

Verifying the write path with --dry-run

A dry run proves that the draft command is well formed and that the guards let it through. It also proves that the same flags refuse sending, because the command lists and the send guard run before the handler, where a dry run stops. The captures below use the script’s write_flags, in a home where me is an alias of you@example.com and gog config no-send set you@example.com has been run.

$ write_flags=(--account me --gmail-no-send --no-input --json --enable-commands-exact gmail.drafts.create)
$ gog "${write_flags[@]}" --dry-run gmail drafts create --thread-id thread-a --reply-all --body-file reply.txt | jq -c '{dry_run, op, thread_id: .request.thread_id, reply_all: .request.reply_all, body_len: .request.body_len}'
{"dry_run":true,"op":"gmail.drafts.create","thread_id":"thread-a","reply_all":true,"body_len":61}

Every send path is refused with exit code 2, even with --dry-run. With --json, each refusal also prints an error object on stdout; only the stderr line is shown for the last 3:

$ gog "${write_flags[@]}" --dry-run gmail send --to friend@example.com --subject t --body b
command "gmail send" is not enabled (set --enable-commands or --enable-commands-exact to allow it)
{"error":{"class":"usage","code":2,"message":"command \"gmail send\" is not enabled (set --enable-commands or --enable-commands-exact to allow it)"}}
$ gog "${write_flags[@]}" --dry-run send --to friend@example.com --subject t --body b
command "send" is not enabled (set --enable-commands or --enable-commands-exact to allow it)
$ gog "${write_flags[@]}" --dry-run gmail reply m1 --body b
command "gmail reply" is not enabled (set --enable-commands or --enable-commands-exact to allow it)
$ gog "${write_flags[@]}" --dry-run gmail drafts send r1
command "gmail drafts send" is not enabled (set --enable-commands or --enable-commands-exact to allow it)

gog reports the allowlist refusal first because it checks the allowlist before the send guard. Remove it, and the account’s config guard refuses the same commands:

$ gog --account me --no-input --dry-run gmail drafts send r1
Gmail sending is blocked for you@example.com (config no-send)
$ echo $?
2

Glossary

Access token
A short-lived credential that gog obtains from a refresh token and sends with each Google API request. A token passed directly with --access-token expires after about 1 hour and is not refreshed.
Account alias
A short name for an account address, set with gog auth alias set, such as me for you@example.com. default and auto are reserved and cannot be aliases.
Agent skill
A short instruction file that teaches a coding agent which gog commands exist and how to use them. gog publishes a core skill, one skill per service and several workflow skills.
Baked binary
A gog executable built by build-safe.sh with a safety profile compiled in. Its version carries a -safe suffix.
Client name
The label that selects one OAuth client’s credentials file and its separate token bucket, chosen with --client or GOG_CLIENT. The default name is default.
Command allowlist
The list of commands that may run, set with --enable-commands (prefix match) or --enable-commands-exact (exact match). Commands are written as dot paths such as gmail.drafts.create.
Command denylist
The list of commands that may not run, set with --disable-commands. It matches command paths, so each send path must be listed separately.
Default account
The account gog uses when neither --account nor GOG_ACCOUNT is set.
Dry run
A run with --dry-run (also -n), in which a command validates its input, prints the action it would take and exits 0 without contacting Google.
Envelope
The JSON object that wraps a list result, for example threads together with nextPageToken, count and has_more. --results-only removes it.
Exit code class
The stable name gog gives each exit code, such as usage for 2 or auth_required for 4. It appears as class in JSON error objects and in gog schema.
Gmail send guard
gog’s block on every command that delivers mail, enabled with --gmail-no-send, GOG_GMAIL_NO_SEND, the config key gmail_no_send or a per-account entry from gog config no-send set.
History ID
A Gmail counter that increases with every mailbox change. gog gmail history --since <historyId> lists messages added after it.
Keyring
The secure store in which gog keeps refresh tokens and OAuth client secrets: the operating system’s keyring, or an encrypted file backend selected with GOG_KEYRING_BACKEND=file and opened with GOG_KEYRING_PASSWORD.
MCP server
The server started by gog mcp, which offers typed tools such as gmail_search to agent clients over the Model Context Protocol. Write tools need --allow-write, and sending needs --allow-gmail-send in addition.
OAuth client
The client ID and secret, downloaded from the Google Cloud console as a JSON file for a desktop app, that identify gog to Google during sign-in. You install it with gog auth credentials.
OAuth scope
A named permission, written as a URL such as https://www.googleapis.com/auth/gmail.readonly, that you approve on Google’s consent screen. Google rejects any call that the token’s scopes do not cover.
Refresh token
The long-lived credential that gog auth add stores in the keyring for one account and one client name. gog exchanges it for access tokens as needed.
Runtime read-only guard
The check enabled by --readonly or GOG_READONLY=1 that rejects mutating HTTP requests just before gog sends them. With gog auth add, the same flag requests read-only scopes.
Safety profile
A YAML policy that allows or blocks command paths and can lock boolean flags. The presets are agent-safe, readonly and full.
Schema
The machine-readable description that gog schema prints: the command tree with arguments and flags, the exit codes, the output formats and the safety state of the current invocation.
Untrusted-content wrapping
The --wrap-untrusted option, which marks text fetched from Google in JSON output as external content, so that a language model can tell it apart from instructions.

Privacy Policy of the gog CLI OAuth App

The author of this book, conao3, registered the Google OAuth app “gog CLI” in a personal Google Cloud project. The app lets the gog command-line client access Gmail and Google Calendar on the author’s own accounts.

Who uses the app

The app is private and reserved for the author’s own Google accounts.

Data the app accesses

When the author runs gog, the app requests access to Gmail and Google Calendar through the OAuth scopes that the author approves on Google’s consent screen. Depending on the command, gog reads messages, threads, labels, drafts, calendars and events, and creates or changes drafts, labels and events.

How the data is used and stored

  • gog runs on the author’s own computers. gog displays the mail and calendar data it fetches in the terminal or passes it to the author’s local scripts and tools.
  • The OAuth client secret and the refresh tokens are stored in the operating system keyring of those computers.
  • The data is not sent to any server operated by the author, is not sold, and is not shared with third parties.
  • The use and transfer of information received from Google APIs adhere to the Google API Services User Data Policy, including the Limited Use requirements.

Revoking access

Access can be withdrawn at any time on the Third-party apps and services page of the Google Account. Running gog auth remove <email> deletes the token from the local keyring.

Contact

For questions about this policy, contact the author through their GitHub profile at github.com/conao3.