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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A Gmail message.//!//! What is filled in depends on which `format` was asked for, and the//! difference is the whole reason there is more than one://!//! - `minimal` -- ids, labels, snippet, dates. No headers, no body. This is//! the cheap one, and it is what a label resync wants.//! - `metadata` -- the above plus the headers, optionally only the headers//! named. No body. Available to the `gmail.metadata` scope, which is the//! narrowest scope that can see a `Subject:`.//! - `full` -- the above plus the parsed MIME tree, with the bodies decoded//! into `MessagePart.body.data`.//! - `raw` -- the above plus `raw`: the whole RFC 5322 message as bytes,//! which is what goes into a maildir.//!//! The strings and the part tree are borrowed from the arena of whatever//! parsed them, so a `Message` must not outlive it.
const Message = @This();
const std = @import("std");
const json = @import("json.zig");
/// Immutable and permanent. Opaque -- Gmail happens to render it as/// lowercase hexadecimal, but nothing documents that and nothing here relies/// on it.id: []const u8,/// The thread this message is part of. The first message of a thread has a/// `thread_id` equal to its own `id`.thread_id: []const u8,/// Absent for `format=raw` unless the message has labels; empty for a message/// that has none.label_ids: []const []const u8 = &.{},/// A short plain-text extract Gmail makes, HTML entities and all.snippet: ?[]const u8 = null,/// The mailbox history record this message was last touched at. Sent as a/// quoted decimal string; see `json.unsigned64`.history_id: ?u64 = null,/// Milliseconds since the Unix epoch. Gmail's own idea of when the message/// arrived for a received message, and the `Date:` header for a sent one --/// which is why it is signed: a message whose header claims 1900 gets a/// negative one.internal_date: ?i64 = null,/// Gmail's estimate of the message size in bytes. An estimate: it is not the/// length of `raw`.size_estimate: ?u32 = null,/// The MIME tree. `format=full` and `format=metadata` only.payload: ?MessagePart = null,/// The entire RFC 5322 message, already base64url-decoded. `format=raw`/// only.raw: ?[]const u8 = null,
/// One node of the MIME tree. A message with no attachments has a payload/// with a `body` and no `parts`; a `multipart/*` has `parts` and an empty/// `body`.pub const MessagePart = struct { /// `""` for the root, then `0`, `0.1`, and so on down the tree. part_id: ?[]const u8 = null, mime_type: ?[]const u8 = null, /// Set for an attachment, empty otherwise. filename: ?[]const u8 = null, headers: []const Header = &.{}, body: ?Body = null, parts: []const MessagePart = &.{},
/// The value of the first header with this name, compared /// case-insensitively because RFC 5322 field names are. /// /// First rather than only: `Received:` legitimately repeats, and so does /// anything a mailing list adds. `headerAll` is the one that returns them /// all. pub fn header(p: *const MessagePart, name: []const u8) ?[]const u8 { for (p.headers) |h| { if (std.ascii.eqlIgnoreCase(h.name, name)) return h.value; } return null; }
/// Walks the tree depth-first, this node first, looking for the first /// part with this MIME type. pub fn findByMimeType(p: *const MessagePart, mime_type: []const u8) ?*const MessagePart { if (p.mime_type) |m| { if (std.ascii.eqlIgnoreCase(m, mime_type)) return p; } for (p.parts) |*child| { if (child.findByMimeType(mime_type)) |found| return found; } return null; }
/// Whether this part is an attachment rather than body text: Gmail says /// so by giving it a filename and putting its content behind an /// `attachment_id` instead of inline. pub fn isAttachment(p: *const MessagePart) bool { const f = p.filename orelse return false; return f.len > 0; }};
pub const Header = struct { name: []const u8, value: []const u8,};
pub const Body = struct { /// Present when the content was too big to inline. Fetch it with /// `users.messages.attachments.get`. attachment_id: ?[]const u8 = null, /// The size Gmail reports, which is the decoded size and so need not /// equal `data.len` when `data` is absent. size: ?u32 = null, /// The content, already base64url-decoded. Absent for a `multipart/*` /// part and for an attachment held behind an `attachment_id`. data: ?[]const u8 = null,};
/// How deep a MIME tree this will follow.////// A real message nests three or four deep -- `multipart/mixed` holding a/// `multipart/alternative` holding the two bodies -- and the cap is here/// because the recursion below is real recursion on input from the network./// Parts below it are dropped rather than the message being rejected.pub const max_depth = 32;
pub const ParseError = error{Malformed} || std.mem.Allocator.Error;
/// Reads a message out of an already-parsed JSON value.////// `alloc` should be an arena: the slices built here -- the label list, the/// part tree, the decoded bodies -- are allocated from it and are not freed/// individually.pub fn fromJson(alloc: std.mem.Allocator, value: std.json.Value) ParseError!Message { if (value != .object) return error.Malformed;
const id = json.string(value, "id") orelse return error.Malformed;
return .{ .id = id, // A history entry's message stub sometimes carries only an id. Rather // than fail, take the message as its own thread, which is what a // single-message thread looks like anyway. `""` is treated the same // way as absent, because an empty thread id is not one: taking it // literally would hand the caller a message that belongs to a thread // that cannot be looked up. .thread_id = json.nonEmptyString(value, "threadId") orelse id, .label_ids = try stringList(alloc, value, "labelIds"), .snippet = json.string(value, "snippet"), .history_id = json.unsigned64(value, "historyId"), .internal_date = json.signed64(value, "internalDate"), .size_estimate = json.unsigned(value, "sizeEstimate"), .payload = payload: { const p = json.object(value, "payload") orelse break :payload null; break :payload try partFromJson(alloc, p, 0); }, .raw = try json.base64Url(alloc, value, "raw"), };}
/// The `Date:` of the message as a `std.Io.Timestamp`, from `internal_date`./// `null` when the format asked for did not include one.pub fn timestamp(m: *const Message) ?std.Io.Timestamp { const ms = m.internal_date orelse return null; return .fromNanoseconds(@as(i96, ms) * std.time.ns_per_ms);}
/// The value of a top-level header, for the common case of wanting the/// `Subject:` and not caring about the MIME tree.pub fn header(m: *const Message, name: []const u8) ?[]const u8 { const p = m.payload orelse return null; return p.header(name);}
/// Whether this message carries a label id.pub fn hasLabel(m: *const Message, label_id: []const u8) bool { for (m.label_ids) |l| if (std.mem.eql(u8, l, label_id)) return true; return false;}
fn partFromJson( alloc: std.mem.Allocator, value: std.json.Value, depth: usize,) ParseError!MessagePart { var part: MessagePart = .{ .part_id = json.string(value, "partId"), .mime_type = json.string(value, "mimeType"), .filename = json.string(value, "filename"), .headers = try headersFromJson(alloc, value), .body = body: { const b = json.object(value, "body") orelse break :body null; break :body .{ .attachment_id = json.nonEmptyString(b, "attachmentId"), .size = json.unsigned(b, "size"), .data = try json.base64Url(alloc, b, "data"), }; }, };
if (depth + 1 >= max_depth) return part;
const children = json.array(value, "parts") orelse return part; var list: std.ArrayList(MessagePart) = .empty; try list.ensureTotalCapacityPrecise(alloc, children.len); for (children) |child| { if (child != .object) continue; list.appendAssumeCapacity(try partFromJson(alloc, child, depth + 1)); } part.parts = try list.toOwnedSlice(alloc); return part;}
fn headersFromJson( alloc: std.mem.Allocator, value: std.json.Value,) std.mem.Allocator.Error![]const Header { const items = json.array(value, "headers") orelse return &.{}; var list: std.ArrayList(Header) = .empty; try list.ensureTotalCapacityPrecise(alloc, items.len); for (items) |item| { if (item != .object) continue; const name = json.string(item, "name") orelse continue; list.appendAssumeCapacity(.{ .name = name, // A header with no value is a header that was sent empty, not one // to drop: `X-Spam-Flag:` with nothing after it is meaningful. .value = json.string(item, "value") orelse "", }); } return list.toOwnedSlice(alloc);}
fn stringList( alloc: std.mem.Allocator, value: std.json.Value, name: []const u8,) std.mem.Allocator.Error![]const []const u8 { const items = json.array(value, name) orelse return &.{}; var list: std.ArrayList([]const u8) = .empty; try list.ensureTotalCapacityPrecise(alloc, items.len); for (items) |item| switch (item) { .string => |s| list.appendAssumeCapacity(s), else => {}, }; return list.toOwnedSlice(alloc);}
const testing = std.testing;
const TestMessage = struct { parsed: std.json.Parsed(std.json.Value), arena: std.heap.ArenaAllocator, message: Message,
fn init(text: []const u8) !TestMessage { var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, text, .{}); errdefer parsed.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); errdefer arena.deinit(); const message: Message = try .fromJson(arena.allocator(), parsed.value); return .{ .parsed = parsed, .arena = arena, .message = message }; }
fn deinit(t: *TestMessage) void { t.arena.deinit(); t.parsed.deinit(); }};
test "a minimal message" { var t = try TestMessage.init( \\{"id":"18c1f2a3b4c5d6e7","threadId":"18c1f2a3b4c5d6e0", \\ "labelIds":["UNREAD","INBOX","CATEGORY_PERSONAL"], \\ "snippet":"the quick brown fox","historyId":"9876543210", \\ "internalDate":"1700000000000","sizeEstimate":4096} ); defer t.deinit(); const m = t.message;
try testing.expectEqualStrings("18c1f2a3b4c5d6e7", m.id); try testing.expectEqualStrings("18c1f2a3b4c5d6e0", m.thread_id); try testing.expectEqual(@as(usize, 3), m.label_ids.len); try testing.expect(m.hasLabel("INBOX")); try testing.expect(!m.hasLabel("SENT")); try testing.expectEqual(@as(?u64, 9876543210), m.history_id); try testing.expectEqual(@as(?i64, 1700000000000), m.internal_date); try testing.expectEqual(@as(?u32, 4096), m.size_estimate); try testing.expectEqual(@as(?MessagePart, null), m.payload); try testing.expectEqual( @as(i96, 1700000000) * std.time.ns_per_s, m.timestamp().?.nanoseconds, );}
test "a full message with a MIME tree" { var t = try TestMessage.init( \\{"id":"a1","threadId":"a1","payload":{ \\ "partId":"","mimeType":"multipart/alternative", \\ "headers":[{"name":"Subject","value":"Hello"}, \\ {"name":"From","value":"a@example.com"}, \\ {"name":"Received","value":"one"}, \\ {"name":"Received","value":"two"}], \\ "body":{"size":0}, \\ "parts":[ \\ {"partId":"0","mimeType":"text/plain","filename":"", \\ "body":{"size":11,"data":"aGVsbG8gd29ybGQ"}}, \\ {"partId":"1","mimeType":"text/html","filename":"", \\ "body":{"size":5,"data":"PGI-eDwvYj4"}}, \\ {"partId":"2","mimeType":"application/pdf","filename":"invoice.pdf", \\ "body":{"size":98765,"attachmentId":"ANGjdJ8"}}]}} ); defer t.deinit(); const m = t.message;
try testing.expectEqualStrings("Hello", m.header("subject").?); try testing.expectEqualStrings("a@example.com", m.header("FROM").?); // First, not last: a repeated header keeps its order. try testing.expectEqualStrings("one", m.header("Received").?); try testing.expectEqual(@as(?[]const u8, null), m.header("Bcc"));
const p = m.payload.?; try testing.expectEqual(@as(usize, 3), p.parts.len);
const plain = p.findByMimeType("text/plain").?; try testing.expectEqualStrings("hello world", plain.body.?.data.?); try testing.expect(!plain.isAttachment());
const html = p.findByMimeType("TEXT/HTML").?; try testing.expectEqualStrings("<b>x</b>", html.body.?.data.?);
const pdf = p.findByMimeType("application/pdf").?; try testing.expect(pdf.isAttachment()); try testing.expectEqualStrings("ANGjdJ8", pdf.body.?.attachment_id.?); try testing.expectEqual(@as(?[]const u8, null), pdf.body.?.data); try testing.expectEqual(@as(?u32, 98765), pdf.body.?.size);
try testing.expectEqual(@as(?*const MessagePart, null), p.findByMimeType("image/gif"));}
test "a raw message is decoded" { var t = try TestMessage.init( \\{"id":"a1","threadId":"a1", \\ "raw":"U3ViamVjdDogaGkKCmJvZHkK"} ); defer t.deinit(); try testing.expectEqualStrings("Subject: hi\n\nbody\n", t.message.raw.?);}
test "a message with no labels has an empty list, not a null one" { var t = try TestMessage.init("{\"id\":\"a1\",\"threadId\":\"a1\"}"); defer t.deinit(); try testing.expectEqual(@as(usize, 0), t.message.label_ids.len); try testing.expect(!t.message.hasLabel("INBOX")); try testing.expectEqual(@as(?[]const u8, null), t.message.header("Subject")); try testing.expectEqual(@as(?std.Io.Timestamp, null), t.message.timestamp());}
test "a stub with only an id is its own thread" { var t = try TestMessage.init("{\"id\":\"a1\"}"); defer t.deinit(); try testing.expectEqualStrings("a1", t.message.thread_id);}
test "an empty thread id is the same as none" { // Found by `tests/fuzz.zig`: taken literally, this produced a message // whose thread id could not be fetched. var t = try TestMessage.init("{\"id\":\"a1\",\"threadId\":\"\"}"); defer t.deinit(); try testing.expectEqualStrings("a1", t.message.thread_id);}
test "no id at all is malformed" { var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, "{\"threadId\":\"x\"}", .{}); defer parsed.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); try testing.expectError(error.Malformed, Message.fromJson(arena.allocator(), parsed.value));}
test "a MIME tree deeper than the cap is truncated, not rejected" { var buf: std.ArrayList(u8) = .empty; defer buf.deinit(testing.allocator);
const depth = max_depth + 20; try buf.appendSlice(testing.allocator, "{\"id\":\"a1\",\"payload\":"); for (0..depth) |_| { try buf.appendSlice(testing.allocator, "{\"mimeType\":\"multipart/mixed\",\"parts\":["); } try buf.appendSlice(testing.allocator, "{\"mimeType\":\"text/plain\"}"); for (0..depth) |_| try buf.appendSlice(testing.allocator, "]}"); try buf.appendSlice(testing.allocator, "}");
var t = try TestMessage.init(buf.items); defer t.deinit();
var d: usize = 0; var p: *const MessagePart = &t.message.payload.?; while (p.parts.len > 0) : (d += 1) p = &p.parts[0]; try testing.expectEqual(max_depth - 1, d);}
test "junk inside the arrays is skipped, not fatal" { var t = try TestMessage.init( \\{"id":"a1","labelIds":["INBOX",7,null,"SENT"], \\ "payload":{"headers":[{"name":"A","value":"1"},"nonsense", \\ {"value":"no name"},{"name":"B"}], \\ "parts":[{"mimeType":"text/plain"},42]}} ); defer t.deinit();
try testing.expectEqual(@as(usize, 2), t.message.label_ids.len); try testing.expect(t.message.hasLabel("SENT"));
const p = t.message.payload.?; try testing.expectEqual(@as(usize, 2), p.headers.len); try testing.expectEqualStrings("1", p.header("A").?); // Sent empty, and kept: the header was there. try testing.expectEqualStrings("", p.header("B").?); try testing.expectEqual(@as(usize, 1), p.parts.len);}