Something went wrong. Try again.
A Gmail API client library for Zig: labels, messages, and the mailbox history that turns a second sync into an update.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A command line client for the library: signs in, and then reads a real//! mailbox with what it got.//!//! It exists to be run by hand against something the test suite cannot reach.//! Everything in `tests/` talks to a Gmail written a hundred lines away, so it//! proves the two halves agree with each other; only this proves the library//! agrees with Google.//!//! ```console//! $ zig build run -- login \//! --client-id 1234.apps.googleusercontent.com \//! --client-secret "$(cat secret)" \//! --store ~/.cache/zig-gmail/tokens.json//! $ zig build run -- profile --store ~/.cache/zig-gmail/tokens.json --client-id ...//! $ zig build run -- labels --store ... --client-id ...//! $ zig build run -- messages --query "-in:chat newer_than:2d" --limit 20 --store ... --client-id ...//! $ zig build run -- get 18c1f2a3b4c5d6e7 --format raw --store ... --client-id ...//! $ zig build run -- get 18c1f2a3b4c5d6e7 18c1f2a3b4c5d6e8 --store ... --client-id ...//! $ zig build run -- history --since 8800112233 --store ... --client-id ...//! ```//!//! Every command but `login` needs `--client-id` and `--client-secret` as//! well as `--store`, because refreshing an access token is an authenticated//! request and the credentials are not in the store.//!//! The store holds a refresh token, so it is written 0600 and belongs//! somewhere that stays that way.
const std = @import("std");const gmail = @import("gmail");const oidc = @import("oidc");
const user_agent = "zig-gmail/" ++ @import("build_options").version;
const usage = \\usage: zig-gmail <command> [options] \\ \\Commands: \\ login Sign in with a browser and store the tokens \\ profile Print the mailbox profile, including its history id \\ labels List the labels \\ messages List message ids matching a query \\ get ID [ID...] Fetch one message, or several in one batch \\ history List what has changed since a history id \\ revoke Revoke the grant and delete the stored tokens \\ \\Options: \\ --client-id ID Required by every command \\ --client-secret S Required by every command; Google issues one even \\ for a "desktop" client \\ --store PATH Where the tokens are kept (default \\ $XDG_CACHE_HOME/zig-gmail/tokens.json) \\ --scope S Repeatable. Defaults to gmail.readonly and \\ gmail.labels \\ --user ADDRESS The mailbox. Default "me" \\ \\login: \\ --login-hint S Which account to offer \\ --port N Fix the loopback port \\ --timeout SECONDS How long to wait for the browser (default 300) \\ \\messages: \\ --query Q A Gmail search query \\ --label ID Repeatable \\ --limit N Stop after N messages (default 25, 0 for all) \\ --spam-trash Include spam and trash \\ \\get: \\ --format F minimal, metadata, full (default) or raw \\ --header NAME Repeatable, with --format metadata \\ Several ids go in one batch request, at most \\ 100 of them \\ \\history: \\ --since ID Required. A history id from `profile` \\ --limit N Stop after N records (default 25, 0 for all) \\;
const Command = enum { login, profile, labels, messages, get, history, revoke };
const Format = enum { minimal, metadata, full, raw };
const Options = struct { command: Command = .profile, positionals: std.ArrayList([]const u8) = .empty, client_id: ?[]const u8 = null, client_secret: ?[]const u8 = null, store: ?[]const u8 = null, scopes: std.ArrayList([]const u8) = .empty, user: []const u8 = "me",
login_hint: ?[]const u8 = null, port: u16 = 0, timeout_s: u32 = 300,
query: ?[]const u8 = null, labels: std.ArrayList([]const u8) = .empty, limit: usize = 25, spam_trash: bool = false,
format: Format = .full, headers: std.ArrayList([]const u8) = .empty,
since: ?u64 = null,};
pub fn main(init: std.process.Init) !void { const io = init.io; const gpa = init.gpa;
var stdout_buffer: [16 * 1024]u8 = undefined; var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer); const out = &stdout_writer.interface; defer out.flush() catch {};
var options: Options = .{}; defer options.positionals.deinit(gpa); defer options.scopes.deinit(gpa); defer options.labels.deinit(gpa); defer options.headers.deinit(gpa);
var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.skip();
const command = args.next() orelse return fail(out, usage, .{}); options.command = std.meta.stringToEnum(Command, command) orelse return fail(out, "{s}\nno command called {s}\n", .{ usage, command });
while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--client-id")) { options.client_id = args.next(); } else if (std.mem.eql(u8, arg, "--client-secret")) { options.client_secret = args.next(); } else if (std.mem.eql(u8, arg, "--store")) { options.store = args.next(); } else if (std.mem.eql(u8, arg, "--scope")) { try options.scopes.append(gpa, args.next() orelse return fail(out, usage, .{})); } else if (std.mem.eql(u8, arg, "--user")) { options.user = args.next() orelse "me"; } else if (std.mem.eql(u8, arg, "--login-hint")) { options.login_hint = args.next(); } else if (std.mem.eql(u8, arg, "--port")) { options.port = std.fmt.parseInt(u16, args.next() orelse "0", 10) catch 0; } else if (std.mem.eql(u8, arg, "--timeout")) { options.timeout_s = std.fmt.parseInt(u32, args.next() orelse "300", 10) catch 300; } else if (std.mem.eql(u8, arg, "--query")) { options.query = args.next(); } else if (std.mem.eql(u8, arg, "--label")) { try options.labels.append(gpa, args.next() orelse return fail(out, usage, .{})); } else if (std.mem.eql(u8, arg, "--limit")) { options.limit = std.fmt.parseInt(usize, args.next() orelse "25", 10) catch 25; } else if (std.mem.eql(u8, arg, "--spam-trash")) { options.spam_trash = true; } else if (std.mem.eql(u8, arg, "--format")) { const name = args.next() orelse return fail(out, usage, .{}); options.format = std.meta.stringToEnum(Format, name) orelse return fail(out, "no format called {s}\n", .{name}); } else if (std.mem.eql(u8, arg, "--header")) { try options.headers.append(gpa, args.next() orelse return fail(out, usage, .{})); } else if (std.mem.eql(u8, arg, "--since")) { const text = args.next() orelse return fail(out, usage, .{}); options.since = std.fmt.parseInt(u64, text, 10) catch return fail(out, "--since wants a number, not {s}\n", .{text}); } else if (std.mem.startsWith(u8, arg, "-")) { return fail(out, "{s}\nno option called {s}\n", .{ usage, arg }); } else { try options.positionals.append(gpa, arg); } }
const client_id = options.client_id orelse return fail(out, "--client-id is required\n", .{}); const client_secret = options.client_secret orelse return fail(out, "--client-secret is required\n", .{});
const store_path = try resolveStorePath(gpa, init.environ_map, &options); defer gpa.free(store_path);
// The directory is opened rather than the path being carried around, // because that is what `TokenStore` wants: it is told where, not asked to // work it out. const dirname = std.fs.path.dirname(store_path) orelse "."; var dir = std.Io.Dir.cwd().createDirPathOpen(io, dirname, .{}) catch return fail(out, "cannot open {s}\n", .{dirname}); defer dir.close(io);
var store: gmail.TokenStore = .{ .dir = dir, .path = std.fs.path.basename(store_path), .io = io, };
const scopes: []const []const u8 = if (options.scopes.items.len > 0) options.scopes.items else gmail.scopes.mirror;
if (options.command == .login) { return login(io, gpa, out, &options, &store, client_id, client_secret, scopes); }
var tokens = store.load(gpa) catch |err| switch (err) { error.NoStoredTokens => return fail( out, "no tokens in {s}; run `login` first\n", .{store_path}, ), error.Malformed => return fail(out, "{s} is not a token file\n", .{store_path}), else => |e| return e, }; defer tokens.deinit();
var client: gmail.Client = .{ .oauth = oauthClient(client_id, client_secret, "http://127.0.0.1/callback", scopes), .tokens = &tokens, .user_id = options.user, .user_agent = user_agent, .on_refresh = store.refreshHook(), };
var d: gmail.Client.Diagnostics = .{}; defer d.deinit(gpa);
switch (options.command) { .login => unreachable, .profile => try showProfile(io, gpa, out, &client, &d), .labels => try showLabels(io, gpa, out, &client, &d), .messages => try showMessages(io, gpa, out, &client, &options, &d), .get => try showMessage(io, gpa, out, &client, &options, &d), .history => try showHistory(io, gpa, out, &client, &options, &d), .revoke => try revoke(io, gpa, out, &client, &store, &d), }}
fn oauthClient( client_id: []const u8, client_secret: []const u8, redirect_uri: []const u8, scopes: []const []const u8,) oidc.Client { return .{ .provider = gmail.provider, .client_id = client_id, .client_secret = client_secret, .redirect_uri = redirect_uri, .scopes = scopes, .user_agent = user_agent, };}
fn login( io: std.Io, gpa: std.mem.Allocator, out: *std.Io.Writer, options: *const Options, store: *gmail.TokenStore, client_id: []const u8, client_secret: []const u8, scopes: []const []const u8,) !void { // The listener comes first: the redirect URI has the port in it, and the // port is not known until the socket is bound. var listener = try oidc.loopback.Listener.listen(io, .{ .port = options.port }); defer listener.deinit(io);
const redirect_uri = try listener.redirectUri(gpa); defer gpa.free(redirect_uri);
const client = oauthClient(client_id, client_secret, redirect_uri, scopes);
const rng_source: std.Random.IoSource = .{ .io = io }; var authorization = try client.authorize(gpa, rng_source.interface(), .{ .login_hint = options.login_hint, // Google's own, and not optional: without `access_type=offline` there // is no refresh token and the grant dies in an hour. `prompt=consent` // is what makes Google issue one again on a second sign-in, where it // otherwise remembers having issued one already and sends none. .prompt = "consent", .extra = &.{.{ .name = "access_type", .value = "offline" }}, }); defer authorization.deinit();
try out.print( \\Open this in a browser: \\ \\ {s} \\ \\Listening on {s} \\ , .{ authorization.url, redirect_uri }); try out.flush();
var redirect = listener.wait(io, gpa, .{ .timeout = .{ .duration = .{ .raw = .fromSeconds(options.timeout_s), .clock = .awake, } }, }) catch |err| switch (err) { error.Timeout => return fail( out, "nobody came back within {d} seconds\n", .{options.timeout_s}, ), else => |e| return e, }; defer redirect.deinit();
var d: oidc.Client.Diagnostics = .{}; defer d.deinit(gpa);
var tokens = client.exchange(io, gpa, &authorization, redirect.query, &d) catch |err| { if (d.message()) |m| { try out.print("sign-in failed: {t}: {f}\n", .{ err, m }); } else { try out.print("sign-in failed: {t}\n", .{err}); } try out.flush(); std.process.exit(1); }; defer tokens.deinit();
if (tokens.refresh_token == null) { try out.writeAll( \\warning: no refresh token came back, so this will stop working in \\an hour. Google sends one only with access_type=offline and only \\the first time unless prompt=consent is also sent; both are. \\Revoking the app's access at myaccount.google.com and signing in \\again is what clears the other cause. \\ ); }
try store.save(&tokens); try out.print("signed in; tokens written to {s}\n", .{store.path}); for (tokens.scopes) |s| try out.print(" scope {s}\n", .{s});}
fn showProfile( io: std.Io, gpa: std.mem.Allocator, out: *std.Io.Writer, client: *gmail.Client, d: *gmail.Client.Diagnostics,) !void { var profile = client.getProfile(io, gpa, d) catch |err| return report(out, err, d); defer profile.deinit();
try out.print("address {s}\n", .{profile.value.email_address}); try out.print("messages {?d}\n", .{profile.value.messages_total}); try out.print("threads {?d}\n", .{profile.value.threads_total}); // The number to keep: it is where an incremental sync starts. try out.print("history {?d}\n", .{profile.value.history_id});}
fn showLabels( io: std.Io, gpa: std.mem.Allocator, out: *std.Io.Writer, client: *gmail.Client, d: *gmail.Client.Diagnostics,) !void { var labels = client.listLabels(io, gpa, d) catch |err| return report(out, err, d); defer labels.deinit();
for (labels.value) |label| { try out.print("{s:<24} {s:<8} {s}\n", .{ label.id, @tagName(label.type), label.conventionalName(), }); } try out.print("\n{d} labels\n", .{labels.value.len});}
fn showMessages( io: std.Io, gpa: std.mem.Allocator, out: *std.Io.Writer, client: *gmail.Client, options: *const Options, d: *gmail.Client.Diagnostics,) !void { var it = client.messageIterator(.{ .q = options.query, .label_ids = options.labels.items, .include_spam_trash = options.spam_trash, }); defer it.deinit();
var count: usize = 0; while (try nextOrReport(out, &it, io, gpa, d)) |message| : (count += 1) { if (options.limit != 0 and count >= options.limit) break; try out.print("{s} {s}\n", .{ message.id, message.thread_id }); } try out.print("\n{d} messages\n", .{count}); if (it.next_page_token) |token| { // What an application would store to resume. Printed because the // whole point of exposing it is that the library does not store it. try out.print("more; resume with pageToken {s}\n", .{token}); }}
fn nextOrReport( out: *std.Io.Writer, it: *gmail.Client.MessageIterator, io: std.Io, gpa: std.mem.Allocator, d: *gmail.Client.Diagnostics,) !?gmail.Message { return it.next(io, gpa, d) catch |err| return report(out, err, d);}
fn showMessage( io: std.Io, gpa: std.mem.Allocator, out: *std.Io.Writer, client: *gmail.Client, options: *const Options, d: *gmail.Client.Diagnostics,) !void { const ids = options.positionals.items; if (ids.len == 0) return fail(out, "`get` wants a message id\n", .{});
const get_options: gmail.Client.GetMessageOptions = .{ .format = switch (options.format) { .minimal => .minimal, .metadata => .metadata, .full => .full, .raw => .raw, }, .metadata_headers = options.headers.items, };
if (ids.len == 1) { var message = client.getMessage(io, gpa, ids[0], get_options, d) catch |err| return report(out, err, d); defer message.deinit(); return printMessage(out, message.value); }
// Several ids is what the batch endpoint is for: one request rather than // one per message. `raw` is not, because the point of printing a raw // message is to redirect it into a file that is that message, and several // of them concatenated is not a file of anything. if (options.format == .raw) { return fail(out, "--format raw prints one message; pass one id\n", .{}); } if (ids.len > gmail.batch.max_calls) { return fail(out, "a batch holds at most {d} calls\n", .{gmail.batch.max_calls}); }
var got = client.batchGetMessages(io, gpa, ids, get_options, d) catch |err| return report(out, err, d); defer got.deinit();
for (got.items) |item| { try out.print("== {s}\n", .{item.id}); const message = item.value orelse { // The failure is the call's own: the batch itself succeeded, and // the other messages in it are here. try out.print("{f}\n\n", .{item}); continue; }; try printMessage(out, message); try out.writeAll("\n"); } try out.print("{d} of {d} fetched in one request\n", .{ got.okCount(), got.items.len });}
fn printMessage(out: *std.Io.Writer, m: gmail.Message) !void { // `raw` is the whole message; print it and nothing else, so that the // output can be redirected into a file that is a valid RFC 5322 message. if (m.raw) |raw| return out.writeAll(raw);
try out.print("id {s}\n", .{m.id}); try out.print("thread {s}\n", .{m.thread_id}); try out.print("history {?d}\n", .{m.history_id}); try out.print("date {?d}\n", .{m.internal_date}); try out.print("size {?d}\n", .{m.size_estimate}); try out.writeAll("labels "); for (m.label_ids, 0..) |l, i| try out.print("{s}{s}", .{ if (i == 0) "" else " ", l }); try out.writeAll("\n"); if (m.snippet) |s| try out.print("snippet {s}\n", .{s});
if (m.payload) |payload| { try out.writeAll("\n"); for (payload.headers) |h| try out.print("{s}: {s}\n", .{ h.name, h.value }); try out.writeAll("\n"); try printPart(out, &payload, 0); }}
fn printPart(out: *std.Io.Writer, part: *const gmail.Message.MessagePart, depth: usize) !void { for (0..depth) |_| try out.writeAll(" "); try out.print("{s} {s}", .{ part.part_id orelse "-", part.mime_type orelse "application/octet-stream", }); if (part.isAttachment()) try out.print(" attachment {s}", .{part.filename.?}); if (part.body) |body| { if (body.data) |data| try out.print(" ({d} bytes)", .{data.len}); if (body.attachment_id) |a| try out.print(" (fetch {s})", .{a}); } try out.writeAll("\n"); for (part.parts) |*child| try printPart(out, child, depth + 1);}
fn showHistory( io: std.Io, gpa: std.mem.Allocator, out: *std.Io.Writer, client: *gmail.Client, options: *const Options, d: *gmail.Client.Diagnostics,) !void { const since = options.since orelse return fail(out, "`history` wants --since, which `profile` prints\n", .{});
var it = client.historyIterator(.{ .start_history_id = since }); defer it.deinit();
var count: usize = 0; while (true) { const record = it.next(io, gpa, d) catch |err| switch (err) { // The one failure worth explaining rather than printing: it means // the incremental path is gone, not that anything is broken. error.HistoryTooOld => return fail( out, \\history id {d} has aged out; Gmail keeps about a week of it. \\There is no incremental update from here -- list the mailbox \\in full and start again from the history id `profile` prints. \\ , .{since}, ), else => |e| return report(out, e, d), } orelse break;
if (options.limit != 0 and count >= options.limit) break; count += 1;
try out.print("{d}\n", .{record.id}); var changes = record.changes(); while (changes.next()) |change| { try out.print(" {s:<14} {s}", .{ @tagName(change), change.messageId() }); switch (change) { .labels_added, .labels_removed => |l| { for (l.label_ids) |label| try out.print(" {s}", .{label}); }, else => {}, } try out.writeAll("\n"); } }
try out.print("\n{d} records\n", .{count}); if (it.history_id) |h| try out.print("next time, --since {d}\n", .{h});}
fn revoke( io: std.Io, gpa: std.mem.Allocator, out: *std.Io.Writer, client: *gmail.Client, store: *gmail.TokenStore, d: *gmail.Client.Diagnostics,) !void { // The refresh token, because revoking the access token leaves the grant // standing and the next refresh would simply mint another. const token = client.tokens.refresh_token orelse client.tokens.access_token; client.oauth.revoke(io, gpa, token, "refresh_token", &d.oauth) catch |err| { try out.print("the server would not revoke it: {t}\n", .{err}); }; try store.clear(); try out.writeAll("tokens deleted\n");}
/// `--store`, or `$XDG_CACHE_HOME/zig-gmail/tokens.json`, or/// `$HOME/.cache/...`. Owned by the caller.fn resolveStorePath( gpa: std.mem.Allocator, env: *const std.process.Environ.Map, options: *const Options,) ![]u8 { if (options.store) |p| return gpa.dupe(u8, p);
if (env.get("XDG_CACHE_HOME")) |cache| { if (cache.len > 0) { return std.fs.path.join(gpa, &.{ cache, "zig-gmail", "tokens.json" }); } } const home = env.get("HOME") orelse return error.NoHomeDirectory; return std.fs.path.join(gpa, &.{ home, ".cache", "zig-gmail", "tokens.json" });}
/// Says what went wrong with as much as the diagnostics know, then stops.////// The distinction worth keeping is between a failure the user can do/// something about -- the grant is gone, the scope is too narrow -- and one/// they cannot, and the API error object is what draws it.fn report(out: *std.Io.Writer, err: anyerror, d: *const gmail.Client.Diagnostics) noreturn { out.print("{t}: {f}\n", .{ err, d }) catch {}; switch (err) { error.Unauthorized, error.RefreshFailed => out.writeAll( "the grant is no longer good; run `login` again\n", ) catch {}, error.NoRefreshToken => out.writeAll( "there is no refresh token stored; run `login` again\n", ) catch {}, error.TooManyRetries => out.writeAll( "Gmail kept asking for a slower pace; try again later\n", ) catch {}, else => {}, } if (d.apiError()) |api| { if (api.reason()) |reason| { if (std.mem.eql(u8, reason, "insufficientPermissions")) { out.writeAll( "the stored token's scopes do not cover this; sign in " ++ "again with the --scope this needs\n", ) catch {}; } } } out.flush() catch {}; std.process.exit(1);}
fn fail(out: *std.Io.Writer, comptime fmt: []const u8, args: anytype) noreturn { out.print(fmt, args) catch {}; out.flush() catch {}; std.process.exit(1);}
test { // The CLI has no tests of its own; this is here so that `zig build test` // compiles it, which is what catches it having drifted from the library. std.testing.refAllDecls(@This());}