// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A message in an Outlook mailbox. //! //! What is filled in depends on what `$select` asked for, and that is the first //! thing to understand about this type: **every member but `id` may be absent //! because it was not selected**, and absent is not the same as empty. A //! message whose `is_read` is `null` was not fetched with `isRead` in the //! `$select`; it is not an unread message. Treating one as the other marks a //! mailbox unread. //! //! Graph returns every property when `$select` is left off, so the distinction //! only arises for the narrowed requests that make a mailbox walk fast -- which //! is to say, for the requests anybody walking a mailbox will actually make. //! //! ## The body, and the other body //! //! `body` is the message as Outlook stores it, which is **HTML unless asked //! otherwise** -- a `Prefer: outlook.body-content-type="text"` header is what //! changes that, and `Client.GetMessageOptions.body_type` sends it. It is not //! the message as it arrived: Outlook has already parsed the MIME, and what //! comes back is its rendering rather than the bytes somebody sent. //! //! For the bytes somebody sent, there is `Client.getMime`, which fetches //! `/$value` and returns the RFC 5322 message. That is what belongs in a //! maildir, and it is the reason this type has no MIME tree of its own: Graph //! does not send one. A Gmail client parses `payload.parts`; here the choice is //! between Outlook's flattened `body` and the original message, and a mirror //! wants the original. //! //! ## Ids move //! //! A message id is stable only while the message stays put. **Moving a message //! between folders changes its id**, so a message moved out of the inbox //! arrives in one folder's delta as an addition and in the other's as a //! removal, with nothing to connect them. `internet_message_id` -- the RFC 5322 //! `Message-ID:` -- is what survives, and is what a local store should key on //! if it wants to notice that the two are the same message. //! //! The strings are borrowed from the arena of whatever parsed them. const Message = @This(); const std = @import("std"); const json = @import("json.zig"); /// Opaque, long, and stable only until the message is moved. See the note /// above. id: []const u8, /// `@odata.etag`. What an `If-Match` would carry, and the cheapest way to tell /// whether a message has changed since it was last seen. etag: ?[]const u8 = null, /// The same version, by its other name. Graph sends both. change_key: ?[]const u8 = null, /// Which folder the message is in. parent_folder_id: ?[]const u8 = null, /// The RFC 5322 `Message-ID:`, angle brackets included. Unlike `id`, this /// survives a move -- and, unlike `id`, it is written by whoever sent the /// message, so it is not unique in any sense a security decision may rely on. internet_message_id: ?[]const u8 = null, /// Threading, Outlook's way. Not the same as a `References:` chain. conversation_id: ?[]const u8 = null, conversation_index: ?[]const u8 = null, subject: ?[]const u8 = null, /// The first couple of hundred characters, always as plain text whatever the /// body is. The cheap way to show what a message says. body_preview: ?[]const u8 = null, body: ?ItemBody = null, /// The part of the body that is unique to this message, with the quoted /// history of the conversation removed. Only present when selected. unique_body: ?ItemBody = null, /// When Outlook received it. The one to sort a mailbox by. received_date_time: ?std.Io.Timestamp = null, /// When the sender says it was sent. sent_date_time: ?std.Io.Timestamp = null, created_date_time: ?std.Io.Timestamp = null, last_modified_date_time: ?std.Io.Timestamp = null, /// Who it is from, as the mailbox believes. `sender` is the envelope and /// `from` is the header; they differ when somebody sends on another's behalf. sender: ?Recipient = null, from: ?Recipient = null, to_recipients: []const Recipient = &.{}, cc_recipients: []const Recipient = &.{}, /// Populated only on a message in the sender's own mailbox. A received /// message does not know who else was blind copied, because that is what blind /// means. bcc_recipients: []const Recipient = &.{}, reply_to: []const Recipient = &.{}, is_read: ?bool = null, is_draft: ?bool = null, has_attachments: ?bool = null, is_delivery_receipt_requested: ?bool = null, is_read_receipt_requested: ?bool = null, importance: ?Importance = null, inference_classification: ?InferenceClassification = null, flag: ?FlagStatus = null, /// The user's own categories -- Outlook's coloured tags, which are the nearest /// thing here to a Gmail label. categories: []const []const u8 = &.{}, /// A URL that opens the message in Outlook on the web. web_link: ?[]const u8 = null, /// The RFC 5322 headers, which Graph sends **only** when /// `$select=internetMessageHeaders` asks for them -- and only on a message it /// received, never on one composed in Outlook. internet_message_headers: []const Header = &.{}, /// Set when this came out of a delta query and is a tombstone rather than a /// message: the item is gone and only its `id` is populated. See `isRemoved`. removed: ?Removed = null, pub const Recipient = struct { /// The display name, which is whatever the sender wrote and is not to be /// trusted as identifying anybody. name: ?[]const u8 = null, address: ?[]const u8 = null, }; pub const ItemBody = struct { content_type: BodyType = .html, content: ?[]const u8 = null, }; /// Graph spells these lowercase, which is also how Zig spells enum tags, so /// `std.meta.stringToEnum` does the whole job. pub const BodyType = enum { text, html }; pub const Importance = enum { low, normal, high }; /// Outlook's Focused Inbox, which decides whether a message is shown first or /// in the "Other" tab. Purely advisory, and computed by the service. pub const InferenceClassification = enum { focused, other }; pub const FlagStatus = enum { notFlagged, complete, flagged, pub fn isFlagged(f: FlagStatus) bool { return f == .flagged; } }; pub const Header = struct { name: []const u8, value: []const u8, }; pub const Removed = struct { /// `deleted`, or `changed` for an item that has moved out of the scope /// being tracked. Both mean "it is not here any more"; only the second /// means it may still exist somewhere else. reason: ?[]const u8 = null, pub fn isDeleted(r: Removed) bool { const reason = r.reason orelse return true; return std.mem.eql(u8, reason, "deleted"); } }; /// How many recipients a single list will hold. /// /// Exchange's own limit on recipients is five hundred, and a list longer than /// this is a malformed or hostile response rather than a message anybody sent. /// The excess is dropped rather than the message being rejected. pub const max_recipients = 4096; 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 recipient lists, the categories and the /// headers 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; return .{ .id = json.string(value, "id") orelse return error.Malformed, .etag = json.string(value, "@odata.etag"), .change_key = json.string(value, "changeKey"), .parent_folder_id = json.nonEmptyString(value, "parentFolderId"), .internet_message_id = json.nonEmptyString(value, "internetMessageId"), .conversation_id = json.nonEmptyString(value, "conversationId"), .conversation_index = json.nonEmptyString(value, "conversationIndex"), // Not `nonEmptyString`: a message really can have been sent with an // empty subject, and reporting that as "not selected" would be a lie. .subject = json.string(value, "subject"), .body_preview = json.string(value, "bodyPreview"), .body = itemBody(value, "body"), .unique_body = itemBody(value, "uniqueBody"), .received_date_time = json.dateTime(value, "receivedDateTime"), .sent_date_time = json.dateTime(value, "sentDateTime"), .created_date_time = json.dateTime(value, "createdDateTime"), .last_modified_date_time = json.dateTime(value, "lastModifiedDateTime"), .sender = recipient(json.object(value, "sender")), .from = recipient(json.object(value, "from")), .to_recipients = try recipientList(alloc, value, "toRecipients"), .cc_recipients = try recipientList(alloc, value, "ccRecipients"), .bcc_recipients = try recipientList(alloc, value, "bccRecipients"), .reply_to = try recipientList(alloc, value, "replyTo"), .is_read = json.boolean(value, "isRead"), .is_draft = json.boolean(value, "isDraft"), .has_attachments = json.boolean(value, "hasAttachments"), .is_delivery_receipt_requested = json.boolean(value, "isDeliveryReceiptRequested"), .is_read_receipt_requested = json.boolean(value, "isReadReceiptRequested"), // An enum value nobody has heard of reads as absent rather than // failing the message: a new `importance` next year must not stop a // mailbox walk. .importance = enumOf(Importance, value, "importance"), .inference_classification = enumOf( InferenceClassification, value, "inferenceClassification", ), .flag = flag: { const f = json.object(value, "flag") orelse break :flag null; break :flag enumOf(FlagStatus, f, "flagStatus"); }, .categories = try json.stringList(alloc, value, "categories"), .web_link = json.nonEmptyString(value, "webLink"), .internet_message_headers = try headerList(alloc, value), .removed = removed: { const r = json.object(value, "@removed") orelse break :removed null; break :removed .{ .reason = json.string(r, "reason") }; }, }; } /// Whether this is a tombstone from a delta query rather than a message. /// /// The check every delta loop needs first: a removed item carries an `id` and /// nothing else, so reading its subject or its date would report absent for /// everything and look like a message that simply was not selected. pub fn isRemoved(m: *const Message) bool { return m.removed != null; } /// When the message arrived, falling back to when it was sent and then to when /// it was created. `null` when none of the three was selected. pub fn timestamp(m: *const Message) ?std.Io.Timestamp { return m.received_date_time orelse m.sent_date_time orelse m.created_date_time; } /// The value of an RFC 5322 header, compared case-insensitively because field /// names are. /// /// Only ever finds anything when `internetMessageHeaders` was selected, and /// only on a received message. It returns the *first* match: `Received:` /// legitimately repeats, and so does anything a mailing list adds. pub fn header(m: *const Message, name: []const u8) ?[]const u8 { for (m.internet_message_headers) |h| { if (std.ascii.eqlIgnoreCase(h.name, name)) return h.value; } return null; } /// The sender's address: `from`, falling back to `sender`. /// /// `from` is the header and `sender` the envelope, and where they differ it is /// `from` that a person means by "who sent this". pub fn fromAddress(m: *const Message) ?[]const u8 { if (m.from) |f| if (f.address) |a| if (a.len > 0) return a; if (m.sender) |s| if (s.address) |a| if (a.len > 0) return a; return null; } /// Whether `address` is among the recipients, in any of the three lists. /// Case-insensitively, because the local part of an address is /// case-sensitive in the RFC and in no mail system anybody actually runs. pub fn hasRecipient(m: *const Message, address: []const u8) bool { for ([_][]const Recipient{ m.to_recipients, m.cc_recipients, m.bcc_recipients }) |list| { for (list) |r| { const a = r.address orelse continue; if (std.ascii.eqlIgnoreCase(a, address)) return true; } } return false; } /// Whether the message carries a category, compared exactly: Outlook's /// categories are case-sensitive and two differing only in case are two /// categories. pub fn hasCategory(m: *const Message, category: []const u8) bool { for (m.categories) |c| if (std.mem.eql(u8, c, category)) return true; return false; } fn itemBody(value: std.json.Value, name: []const u8) ?ItemBody { const b = json.object(value, name) orelse return null; return .{ .content_type = enumOf(BodyType, b, "contentType") orelse .html, .content = json.string(b, "content"), }; } fn recipient(value: ?std.json.Value) ?Recipient { const v = value orelse return null; // The address is wrapped one level deeper than it looks: // `{"emailAddress":{"name":..., "address":...}}`. const inner = json.object(v, "emailAddress") orelse return null; return .{ .name = json.string(inner, "name"), .address = json.nonEmptyString(inner, "address"), }; } fn recipientList( alloc: std.mem.Allocator, value: std.json.Value, name: []const u8, ) std.mem.Allocator.Error![]const Recipient { const items = json.array(value, name) orelse return &.{}; const count = @min(items.len, max_recipients); var list: std.ArrayList(Recipient) = .empty; try list.ensureTotalCapacityPrecise(alloc, count); for (items[0..count]) |item| { const r = recipient(item) orelse continue; list.appendAssumeCapacity(r); } return list.toOwnedSlice(alloc); } fn headerList( alloc: std.mem.Allocator, value: std.json.Value, ) std.mem.Allocator.Error![]const Header { const items = json.array(value, "internetMessageHeaders") 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 sent empty is a header that was there: `X-Spam-Flag:` // with nothing after it is meaningful. .value = json.string(item, "value") orelse "", }); } return list.toOwnedSlice(alloc); } fn enumOf(comptime T: type, value: std.json.Value, name: []const u8) ?T { const text = json.string(value, name) orelse return null; return std.meta.stringToEnum(T, text); } 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 "the shape the reference's own example returns" { var t = try TestMessage.init( \\{"@odata.etag":"W/\"CQAAABYAAAC4ofQHEIqCSbQPot83AFcbAAAnjjuZ\"", \\ "id":"AAMkADhMGAAA=","createdDateTime":"2018-09-09T03:15:05Z", \\ "lastModifiedDateTime":"2018-09-09T03:15:08Z", \\ "changeKey":"CQAAABYAAAC4ofQHEIqCSbQPot83AFcbAAAnjjuZ","categories":[], \\ "receivedDateTime":"2018-09-09T03:15:08Z","sentDateTime":"2018-09-09T03:15:06Z", \\ "hasAttachments":false, \\ "internetMessageId":"", \\ "subject":"9/9/2018: concert","bodyPreview":"The group represents Nevada.", \\ "importance":"normal","parentFolderId":"AAMkADcbAAAAAAEJAAA=", \\ "conversationId":"AAQkADOUpag6yWs=","isDeliveryReceiptRequested":false, \\ "isReadReceiptRequested":false,"isRead":true,"isDraft":false, \\ "webLink":"https://outlook.office365.com/owa/?ItemID=AAMkADMGAAA%3D", \\ "inferenceClassification":"focused", \\ "body":{"contentType":"html","content":"The group represents Nevada."}, \\ "sender":{"emailAddress":{"name":"Adele Vance","address":"adelev@contoso.com"}}, \\ "from":{"emailAddress":{"name":"Adele Vance","address":"adelev@contoso.com"}}, \\ "toRecipients":[{"emailAddress":{"name":"Alex Wilber","address":"AlexW@contoso.com"}}], \\ "ccRecipients":[],"bccRecipients":[],"replyTo":[], \\ "flag":{"flagStatus":"notFlagged"}} ); defer t.deinit(); const m = t.message; try testing.expectEqualStrings("AAMkADhMGAAA=", m.id); try testing.expectEqualStrings("9/9/2018: concert", m.subject.?); try testing.expectEqualStrings( "", m.internet_message_id.?, ); try testing.expectEqual(Importance.normal, m.importance.?); try testing.expectEqual(InferenceClassification.focused, m.inference_classification.?); try testing.expectEqual(FlagStatus.notFlagged, m.flag.?); try testing.expect(!m.flag.?.isFlagged()); try testing.expectEqual(@as(?bool, true), m.is_read); try testing.expectEqual(@as(?bool, false), m.has_attachments); try testing.expectEqual(BodyType.html, m.body.?.content_type); try testing.expectEqualStrings("adelev@contoso.com", m.fromAddress().?); try testing.expectEqualStrings("Adele Vance", m.from.?.name.?); try testing.expectEqual(@as(usize, 1), m.to_recipients.len); try testing.expect(m.hasRecipient("alexw@contoso.com")); try testing.expect(!m.hasRecipient("nobody@contoso.com")); try testing.expectEqual( @as(i96, 1536462908) * std.time.ns_per_s, m.timestamp().?.nanoseconds, ); try testing.expect(!m.isRemoved()); // An empty `categories` array is empty, and the etag is readable despite // its name being an OData annotation. try testing.expectEqual(@as(usize, 0), m.categories.len); try testing.expect(std.mem.startsWith(u8, m.etag.?, "W/")); } test "a delta tombstone" { // What the delta reference shows for a deleted message: an id, an // `@removed`, and nothing else at all. var t = try TestMessage.init( \\{"@odata.type":"#microsoft.graph.message", \\ "id":"AAMkADk0MGFkODE3LWE4MmYtNDRhOS0Dh_6qB","@removed":{"reason":"deleted"}} ); defer t.deinit(); try testing.expect(t.message.isRemoved()); try testing.expect(t.message.removed.?.isDeleted()); // The check a delta loop must make first: everything else reads as // absent, which is indistinguishable from a narrow `$select`. try testing.expectEqual(@as(?[]const u8, null), t.message.subject); try testing.expectEqual(@as(?std.Io.Timestamp, null), t.message.timestamp()); } test "`changed` is a removal too, but a different one" { var t = try TestMessage.init("{\"id\":\"a\",\"@removed\":{\"reason\":\"changed\"}}"); defer t.deinit(); try testing.expect(t.message.isRemoved()); // It has moved out of what is being tracked, which is not the same as // being gone. try testing.expect(!t.message.removed.?.isDeleted()); // And a removal with no reason given is treated as a deletion, which is // the safe reading: the item is not here. var u = try TestMessage.init("{\"id\":\"a\",\"@removed\":{}}"); defer u.deinit(); try testing.expect(u.message.removed.?.isDeleted()); } test "absent is not false, which is the whole point of the optionals" { // What `$select=subject,sender` really returns: three members. var t = try TestMessage.init( \\{"id":"a","subject":"x", \\ "sender":{"emailAddress":{"name":"D","address":"d@contoso.com"}}} ); defer t.deinit(); // Not `false`. A message that was not asked about its read state is not an // unread message, and reporting it as one marks a mailbox unread. try testing.expectEqual(@as(?bool, null), t.message.is_read); try testing.expectEqual(@as(?bool, null), t.message.has_attachments); try testing.expectEqual(@as(?Importance, null), t.message.importance); // `sender` alone still answers for the address. try testing.expectEqualStrings("d@contoso.com", t.message.fromAddress().?); } test "an empty subject is a subject, and an empty address is not an address" { var t = try TestMessage.init( \\{"id":"a","subject":"","from":{"emailAddress":{"name":"D","address":""}}} ); defer t.deinit(); // Somebody really did send a message with no subject. try testing.expectEqualStrings("", t.message.subject.?); // But `""` is not somewhere mail can be sent. try testing.expectEqual(@as(?[]const u8, null), t.message.fromAddress()); try testing.expectEqualStrings("D", t.message.from.?.name.?); } test "internet message headers, when they were selected" { var t = try TestMessage.init( \\{"id":"a","internetMessageHeaders":[ \\ {"name":"MIME-Version","value":"1.0"}, \\ {"name":"Content-Type","value":"multipart/report"}, \\ {"name":"Received","value":"one"},{"name":"Received","value":"two"}, \\ {"name":"X-Spam-Flag","value":""}, \\ {"value":"no name"},"nonsense",{"name":"After-Junk","value":"yes"}]} ); defer t.deinit(); const m = t.message; try testing.expectEqualStrings("1.0", m.header("mime-version").?); try testing.expectEqualStrings("multipart/report", m.header("CONTENT-TYPE").?); // First, not last: a repeated header keeps its order. try testing.expectEqualStrings("one", m.header("Received").?); // Sent empty, and kept. try testing.expectEqualStrings("", m.header("X-Spam-Flag").?); try testing.expectEqual(@as(?[]const u8, null), m.header("Bcc")); // Junk in the middle does not lose what comes after it. try testing.expectEqualStrings("yes", m.header("After-Junk").?); } test "an enum value nobody has heard of does not fail the message" { // A mailbox walk must not stop because Microsoft added an importance. var t = try TestMessage.init( \\{"id":"a","importance":"apocalyptic","inferenceClassification":"sideways", \\ "flag":{"flagStatus":"shimmering"},"body":{"contentType":"markdown","content":"x"}} ); defer t.deinit(); try testing.expectEqual(@as(?Importance, null), t.message.importance); try testing.expectEqual(@as(?InferenceClassification, null), t.message.inference_classification); try testing.expectEqual(@as(?FlagStatus, null), t.message.flag); // The body still has its content; only the type fell back. try testing.expectEqual(BodyType.html, t.message.body.?.content_type); try testing.expectEqualStrings("x", t.message.body.?.content.?); } test "categories are case-sensitive, unlike addresses" { var t = try TestMessage.init("{\"id\":\"a\",\"categories\":[\"Red category\",\"zig\"]}"); defer t.deinit(); try testing.expect(t.message.hasCategory("zig")); // Two categories differing only in case are two categories, which is how // Outlook treats them. try testing.expect(!t.message.hasCategory("Zig")); try testing.expect(!t.message.hasCategory("blue")); } test "junk inside the recipient lists is skipped, not fatal" { var t = try TestMessage.init( \\{"id":"a","toRecipients":[ \\ {"emailAddress":{"address":"one@x"}},42,null,{}, \\ {"emailAddress":"not an object"}, \\ {"emailAddress":{"address":"two@x"}}], \\ "ccRecipients":"not a list"} ); defer t.deinit(); try testing.expectEqual(@as(usize, 2), t.message.to_recipients.len); try testing.expect(t.message.hasRecipient("TWO@X")); try testing.expectEqual(@as(usize, 0), t.message.cc_recipients.len); } test "a recipient list longer than the cap is truncated, not rejected" { var buf: std.ArrayList(u8) = .empty; defer buf.deinit(testing.allocator); try buf.appendSlice(testing.allocator, "{\"id\":\"a\",\"toRecipients\":["); for (0..max_recipients + 100) |i| { if (i != 0) try buf.append(testing.allocator, ','); try buf.appendSlice(testing.allocator, "{\"emailAddress\":{\"address\":\"x@y\"}}"); } try buf.appendSlice(testing.allocator, "]}"); var t = try TestMessage.init(buf.items); defer t.deinit(); try testing.expectEqual(max_recipients, t.message.to_recipients.len); } test "the date falls back through the three it might have" { { var t = try TestMessage.init("{\"id\":\"a\",\"sentDateTime\":\"2020-01-01T00:00:00Z\"}"); defer t.deinit(); try testing.expectEqual( @as(i96, 1577836800) * std.time.ns_per_s, t.message.timestamp().?.nanoseconds, ); } { var t = try TestMessage.init("{\"id\":\"a\"}"); defer t.deinit(); try testing.expectEqual(@as(?std.Io.Timestamp, null), t.message.timestamp()); } } test "no id at all is malformed" { var parsed = try std.json.parseFromSlice( std.json.Value, testing.allocator, "{\"subject\":\"no id\"}", .{}, ); 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)); }