// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Whole messages, of the shapes that actually arrive. //! //! The unit tests beside each parser check one thing each; these check that //! the pieces agree with one another over a message somebody could have been //! sent. Each fixture is written the way the software that produces that shape //! writes it — Outlook's `----=_NextPart_` boundaries and its `name=` on the //! `Content-Type`, Thunderbird's RFC 2231 filenames, a mailing list's //! `multipart/digest` — because the disagreements between implementations are //! the whole difficulty of this format, and a fixture written to suit the //! parser would hide them. //! //! The property every one of them is checked against is that a parsed message //! written back out is the message that went in, byte for byte. That is worth //! more than it sounds: it says the parser kept the preamble, the epilogue, //! the exact folding of every header, the boundary as written, and the body in //! its original encoding — and so that a signed message can be parsed, //! inspected and forwarded with its signature intact. const std = @import("std"); const Io = std.Io; const testing = std.testing; const mime = @import("mime"); /// Parse, write, and insist on getting the same bytes back. fn expectExactRoundTrip(source: []const u8) !mime.Message { var message: mime.Message = try .parse(testing.allocator, source, .{}); errdefer message.deinit(); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); try testing.expectEqualStrings(source, written); return message; } const outlook = "Return-Path: \r\n" ++ "Received: from mail.example.com (mail.example.com [192.0.2.25])\r\n" ++ "\tby mx.example.net (Postfix) with ESMTPS id 3F2A1C0A\r\n" ++ "\tfor ; Tue, 1 Jul 2003 10:52:38 +0200 (CEST)\r\n" ++ "From: \"Ollie, Jeff\" \r\n" ++ "To: Alice , Bob \r\n" ++ "Subject: =?utf-8?Q?Re=3A_the_caf=C3=A9_report?=\r\n" ++ "Date: Tue, 1 Jul 2003 10:52:37 +0200\r\n" ++ "Message-ID: <000001c34000$1a2b3c4d$0a00a8c0@EXAMPLE>\r\n" ++ "MIME-Version: 1.0\r\n" ++ "Content-Type: multipart/mixed;\r\n" ++ "\tboundary=\"----=_NextPart_000_0001_01C34011.1A2B3C4D\"\r\n" ++ "X-Mailer: Microsoft Outlook, Build 10.0.2627\r\n" ++ "\r\n" ++ "This is a multi-part message in MIME format.\r\n" ++ "\r\n" ++ "------=_NextPart_000_0001_01C34011.1A2B3C4D\r\n" ++ "Content-Type: multipart/alternative;\r\n" ++ "\tboundary=\"----=_NextPart_001_0002_01C34011.1A2B3C4D\"\r\n" ++ "\r\n" ++ "------=_NextPart_001_0002_01C34011.1A2B3C4D\r\n" ++ "Content-Type: text/plain;\r\n" ++ "\tcharset=\"iso-8859-1\"\r\n" ++ "Content-Transfer-Encoding: quoted-printable\r\n" ++ "\r\n" ++ "The caf=E9 report is attached.\r\n" ++ "\r\n" ++ "------=_NextPart_001_0002_01C34011.1A2B3C4D\r\n" ++ "Content-Type: text/html;\r\n" ++ "\tcharset=\"iso-8859-1\"\r\n" ++ "Content-Transfer-Encoding: quoted-printable\r\n" ++ "\r\n" ++ "The caf=E9 report is attached.\r\n" ++ "\r\n" ++ "------=_NextPart_001_0002_01C34011.1A2B3C4D--\r\n" ++ "\r\n" ++ "------=_NextPart_000_0001_01C34011.1A2B3C4D\r\n" ++ "Content-Type: application/pdf;\r\n" ++ "\tname=\"=?utf-8?B?Y2Fmw6kucGRm?=\"\r\n" ++ "Content-Transfer-Encoding: base64\r\n" ++ "Content-Disposition: attachment;\r\n" ++ "\tfilename=\"=?utf-8?B?Y2Fmw6kucGRm?=\"\r\n" ++ "\r\n" ++ "JVBERi0xLjQK\r\n" ++ "\r\n" ++ "------=_NextPart_000_0001_01C34011.1A2B3C4D--\r\n"; test "a message from Outlook" { var message = try expectExactRoundTrip(outlook); defer message.deinit(); try testing.expectEqualStrings("Re: the café report", (try message.root.subject()).?); try testing.expect(message.root.media_type.is("multipart", "mixed")); // Three `Received`-style headers exist in real mail; here there is one, // and it survived its folding exactly. try testing.expectEqual(1, message.root.headers.count("received")); try testing.expect(std.mem.find( u8, (try message.root.headers.getUnfolded("received")).?, "by mx.example.net", ) != null); var to = try message.root.addresses(testing.allocator, "to"); defer to.deinit(testing.allocator); try testing.expectEqual(2, to.addresses.len); try testing.expectEqualStrings("Alice", to.addresses[0].mailbox.display_name.?); try testing.expectEqualStrings("bob", to.addresses[1].mailbox.local_part); // The plain text alternative, decoded out of quoted-printable and out of // ISO-8859-1. const plain = message.root.find("text", "plain").?; const text = try plain.textAlloc(testing.allocator); defer testing.allocator.free(text); try testing.expectEqualStrings("The café report is attached.\r\n", text); // The attachment, whose name is spelled as an encoded word in a place the // grammar does not allow one, twice over. const pdf = message.root.find("application", "pdf").?; try testing.expect(pdf.isAttachment()); try testing.expectEqualStrings("café.pdf", (try pdf.filename()).?); const bytes = try pdf.decodeAlloc(testing.allocator); defer testing.allocator.free(bytes); try testing.expectEqualStrings("%PDF-1.4\n", bytes); // Five entities: the mixed, the alternative, the two texts and the file. var count: usize = 0; var walker = message.root.walk(); while (walker.next()) |_| count += 1; try testing.expectEqual(5, count); } const thunderbird = "From: Jeff Ollie \r\n" ++ "To: alice@example.net\r\n" ++ "Subject: =?UTF-8?B?RGllIEdyw7bDn2VuIGF1cyBNw7xuY2hlbg==?=\r\n" ++ "Date: Sat, 12 Sep 2026 09:00:00 -0500\r\n" ++ "MIME-Version: 1.0\r\n" ++ "Content-Type: multipart/mixed; boundary=\"------------abc123def456\"\r\n" ++ "\r\n" ++ "--------------abc123def456\r\n" ++ "Content-Type: text/plain; charset=UTF-8; format=flowed\r\n" ++ "Content-Transfer-Encoding: 8bit\r\n" ++ "\r\n" ++ "Schöne Grüße\r\n" ++ "\r\n" ++ "--------------abc123def456\r\n" ++ "Content-Type: text/csv; charset=UTF-8;\r\n" ++ " name=\"Quartalsbericht f\\u00fcr M\\u00fcnchen.csv\"\r\n" ++ "Content-Disposition: attachment;\r\n" ++ " filename*0*=UTF-8''Quartalsbericht%20f%C3%BCr%20;\r\n" ++ " filename*1*=M%C3%BCnchen.csv\r\n" ++ "Content-Transfer-Encoding: base64\r\n" ++ "\r\n" ++ "YSxiLGMK\r\n" ++ "--------------abc123def456--\r\n"; test "a message from Thunderbird, with a split filename" { var message = try expectExactRoundTrip(thunderbird); defer message.deinit(); try testing.expectEqualStrings("Die Größen aus München", (try message.root.subject()).?); const csv = message.root.find("text", "csv").?; // `Content-Disposition` wins over the `name` on the `Content-Type`, which // here is deliberately written in a notation that means nothing to // anybody — as it does in the messages this is copied from. try testing.expectEqualStrings( "Quartalsbericht für München.csv", (try csv.filename()).?, ); const data = try csv.decodeAlloc(testing.allocator); defer testing.allocator.free(data); try testing.expectEqualStrings("a,b,c\n", data); // An 8bit body is its own decoding, and its charset is declared. const plain = message.root.find("text", "plain").?; try testing.expectEqual(mime.transfer_encoding.TransferEncoding.eight_bit, plain.transferEncoding()); try testing.expectEqualStrings("flowed", plain.media_type.parameters.get("format").?); const text = try plain.textAlloc(testing.allocator); defer testing.allocator.free(text); try testing.expectEqualStrings("Schöne Grüße\r\n", text); } const forwarded = "From: alice@example.net\r\n" ++ "Subject: Fwd: the original\r\n" ++ "MIME-Version: 1.0\r\n" ++ "Content-Type: multipart/mixed; boundary=\"F\"\r\n" ++ "\r\n" ++ "--F\r\n" ++ "Content-Type: text/plain\r\n" ++ "\r\n" ++ "See below.\r\n" ++ "--F\r\n" ++ "Content-Type: message/rfc822\r\n" ++ "Content-Disposition: inline\r\n" ++ "\r\n" ++ "From: bob@example.org\r\n" ++ "Subject: the original\r\n" ++ "Date: Tue, 01 Jul 2003 10:52:37 +0200\r\n" ++ "Content-Type: text/plain\r\n" ++ "\r\n" ++ "the original body\r\n" ++ "--F--\r\n"; test "a forwarded message" { var message = try expectExactRoundTrip(forwarded); defer message.deinit(); const attached = message.root.find("message", "rfc822").?; const inner = attached.body.message; try testing.expectEqualStrings("the original", (try inner.subject()).?); // No trailing line ending: the CRLF in front of `--F--` belongs to the // delimiter, not to the message inside the part. try testing.expectEqualStrings("the original body", inner.body.raw); const sent = (try inner.sentAt()).?; try testing.expectEqual(1057049557, @divTrunc(sent.time.toInstant().timestamp, std.time.ns_per_s)); // The walk reaches into the attached message, which is what makes // `find` able to see through it. var subtypes: std.ArrayList([]const u8) = .empty; defer subtypes.deinit(testing.allocator); var walker = message.root.walk(); while (walker.next()) |part| try subtypes.append(testing.allocator, part.media_type.subtype); try testing.expectEqual(4, subtypes.items.len); try testing.expectEqualStrings("rfc822", subtypes.items[2]); try testing.expectEqualStrings("plain", subtypes.items[3]); } const digest = "From: list@example.net\r\n" ++ "Subject: Digest, Vol 1, Issue 1\r\n" ++ "MIME-Version: 1.0\r\n" ++ "Content-Type: multipart/digest; boundary=\"D\"\r\n" ++ "\r\n" ++ "--D\r\n" ++ "\r\n" ++ "From: a@example.org\r\n" ++ "Subject: first\r\n" ++ "\r\n" ++ "one\r\n" ++ "--D\r\n" ++ "\r\n" ++ "From: b@example.org\r\n" ++ "Subject: second\r\n" ++ "\r\n" ++ "two\r\n" ++ "--D--\r\n"; test "a digest, whose parts default to message/rfc822" { var message = try expectExactRoundTrip(digest); defer message.deinit(); const parts = message.root.body.multipart.parts.items; try testing.expectEqual(2, parts.len); for (parts, [_][]const u8{ "first", "second" }) |part, subject| { // No `Content-Type` on any of these, and yet none of them is // `text/plain`: RFC 2046 §5.1.5 changes the default inside a digest, // and getting it wrong turns each message into its own headers as // text. try testing.expect(part.media_type.is("message", "rfc822")); try testing.expectEqualStrings(subject, (try part.body.message.subject()).?); } } test "a message whose lines end in LF is repaired" { const unix = "From: jeff@example.com\n" ++ "Subject: hello\n" ++ "\n" ++ "body\n"; var message: mime.Message = try .parse(testing.allocator, unix, .{}); defer message.deinit(); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); // The headers come back canonical; the body is bytes and is left alone. try testing.expectEqualStrings( "From: jeff@example.com\r\nSubject: hello\r\n\r\nbody\n", written, ); // And the repair is idempotent, which is the property the fuzz target // checks over everything else. var again: mime.Message = try .parse(testing.allocator, written, .{}); defer again.deinit(); const twice = try again.toBytesAlloc(testing.allocator); defer testing.allocator.free(twice); try testing.expectEqualStrings(written, twice); } test "a message built here is a message read by here" { var prng: std.Random.DefaultPrng = .init(0x5eeded); const random = prng.random(); var message: mime.Message = try .init(testing.allocator); defer message.deinit(); try message.root.setAddresses("From", &.{ .{ .display_name = "Ollie, Jeff", .local_part = "jeff", .domain = "example.com" }, }); try message.root.setAddresses("To", &.{ .{ .display_name = "José García", .local_part = "jose", .domain = "example.net" }, .{ .local_part = "alice", .domain = "example.org" }, }); try message.root.setSubject("Grüße — and a subject long enough to need folding as well as encoding"); try message.root.setMessageId("example.com", random); try message.setText("Schöne Grüße aus München.\nZeile zwei.\n", .{}); _ = try message.attach(random, "a,b,c\n", .{ .content_type = "text/csv", .filename = "Quartalsbericht für München.csv", }); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); // Nothing but ASCII, and no line longer than the hard limit: what came out // is a message a 1982 transport could carry. var lines = std.mem.splitSequence(u8, written, "\r\n"); while (lines.next()) |line| { try testing.expect(line.len <= 998); for (line) |c| try testing.expect(c < 0x80); } var read: mime.Message = try .parse(testing.allocator, written, .{}); defer read.deinit(); try testing.expectEqualStrings( "Grüße — and a subject long enough to need folding as well as encoding", (try read.root.subject()).?, ); var to = try read.root.addresses(testing.allocator, "to"); defer to.deinit(testing.allocator); try testing.expectEqual(2, to.addresses.len); try testing.expectEqualStrings("José García", to.addresses[0].mailbox.display_name.?); try testing.expectEqualStrings("alice", to.addresses[1].mailbox.local_part); const plain = read.root.find("text", "plain").?; const text = try plain.textAlloc(testing.allocator); defer testing.allocator.free(text); try testing.expectEqualStrings("Schöne Grüße aus München.\r\nZeile zwei.\r\n", text); const csv = read.root.find("text", "csv").?; try testing.expectEqualStrings("Quartalsbericht für München.csv", (try csv.filename()).?); const data = try csv.decodeAlloc(testing.allocator); defer testing.allocator.free(data); try testing.expectEqualStrings("a,b,c\n", data); // And what was written is a fixed point. const again = try read.toBytesAlloc(testing.allocator); defer testing.allocator.free(again); try testing.expectEqualStrings(written, again); } test "a message with nothing in it" { var message: mime.Message = try .parse(testing.allocator, "", .{}); defer message.deinit(); try testing.expectEqual(0, message.root.headers.fields.items.len); try testing.expect(message.root.media_type.is("text", "plain")); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); try testing.expectEqualStrings("", written); } test "a message truncated inside its headers does not grow a body" { // The blank line that separates the headers from the body was never // sent, and writing one in would invent a body boundary. This is the // shape a `message/rfc822` part takes when the reporting system kept // only what it had. const truncated = "From: jeff@example.com\r\nSubject: Lunch\r\n"; var message: mime.Message = try .parse(testing.allocator, truncated, .{}); defer message.deinit(); try testing.expect(!message.root.headers_terminated); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); try testing.expectEqualStrings(truncated, written); } test "the shape a mailer actually produces for an HTML message" { var prng: std.Random.DefaultPrng = .init(0x0a11e); const random = prng.random(); var message: mime.Message = try .init(testing.allocator); defer message.deinit(); try message.root.setAddresses("From", &.{ .{ .display_name = "Jeff Ollie", .local_part = "jeff", .domain = "example.com" }, }); try message.root.setSubject("Der Quartalsbericht"); // The identifier has to exist before the HTML that refers to it does. const logo = try message.newContentId("example.com", random); var html: Io.Writer.Allocating = .init(testing.allocator); defer html.deinit(); try html.writer.print( "

Grüße!

\"logo\"", .{logo}, ); try message.setAlternative(random, "Grüße!\n\n[logo]\n", html.written(), .{}); _ = try message.embed(random, "\x89PNG\r\n\x1a\n not really", .{ .filename = "logo.png", .content_id = logo, }); _ = try message.attach(random, "Umsatz;Jahr\n1;2026\n", .{ .filename = "Quartalsbericht für München.csv", }); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); // Nothing but ASCII, and no line over the hard limit. var lines = std.mem.splitSequence(u8, written, "\r\n"); while (lines.next()) |line| { try testing.expect(line.len <= 998); for (line) |c| try testing.expect(c < 0x80); } var read: mime.Message = try .parse(testing.allocator, written, .{}); defer read.deinit(); // multipart/mixed // multipart/related type="multipart/alternative" // multipart/alternative // text/plain // text/html // image/png inline, Content-ID // text/csv attachment try testing.expect(read.root.media_type.is("multipart", "mixed")); const outer = read.root.body.multipart.parts.items; try testing.expectEqual(2, outer.len); const related = outer[0]; try testing.expect(related.media_type.is("multipart", "related")); try testing.expectEqualStrings("multipart/alternative", related.media_type.parameters.get("type").?); try testing.expectEqual(2, related.body.multipart.parts.items.len); const alternative = related.body.multipart.parts.items[0]; try testing.expect(alternative.media_type.is("multipart", "alternative")); try testing.expect(alternative.body.multipart.parts.items[0].media_type.is("text", "plain")); try testing.expect(alternative.body.multipart.parts.items[1].media_type.is("text", "html")); // The `cid:` in the HTML resolves to the image, which is the whole point // of `multipart/related`. const rendered = try alternative.body.multipart.parts.items[1].textAlloc(testing.allocator); defer testing.allocator.free(rendered); const start = std.mem.find(u8, rendered, "cid:").?; const end = std.mem.findScalarPos(u8, rendered, start, '"').?; const image = read.root.findContentId(rendered[start..end]).?; try testing.expect(image.media_type.is("image", "png")); try testing.expectEqualStrings("inline", image.disposition().?); try testing.expect(!image.isAttachment()); const png = try image.decodeAlloc(testing.allocator); defer testing.allocator.free(png); try testing.expectEqualStrings("\x89PNG\r\n\x1a\n not really", png); // The attachment took its media type from its name and kept that name. const csv = outer[1]; try testing.expect(csv.media_type.is("text", "csv")); try testing.expect(csv.isAttachment()); try testing.expectEqualStrings("Quartalsbericht für München.csv", (try csv.filename()).?); // And the whole thing is a fixed point. const again = try read.toBytesAlloc(testing.allocator); defer testing.allocator.free(again); try testing.expectEqualStrings(written, again); } const thunderbird_flowed = "From: Jeff Ollie \r\n" ++ "Subject: A flowed message\r\n" ++ "MIME-Version: 1.0\r\n" ++ "Content-Type: text/plain; charset=UTF-8; format=flowed\r\n" ++ "Content-Transfer-Encoding: 8bit\r\n" ++ "\r\n" ++ "This is a paragraph that the sender's composer wrapped, and \r\n" ++ "which a reader is free to wrap somewhere else entirely.\r\n" ++ "\r\n" ++ "> A quotation, also wrapped by the composer, which joins \r\n" ++ "> back into one line of its own.\r\n" ++ "\r\n" ++ // Two spaces on the wire: the author's one, and the stuffing that lets it // survive being read back. " A line that begins with a space, stuffed so that it survives.\r\n" ++ "-- \r\n" ++ "Jeff\r\n"; test "a format=flowed message from a composer that wraps" { var message = try expectExactRoundTrip(thunderbird_flowed); defer message.deinit(); try testing.expect(message.root.media_type.isFlowed()); const text = try message.root.textAlloc(testing.allocator); defer testing.allocator.free(text); try testing.expectEqualStrings( "This is a paragraph that the sender's composer wrapped, and which a " ++ "reader is free to wrap somewhere else entirely.\r\n" ++ "\r\n" ++ ">A quotation, also wrapped by the composer, which joins back into " ++ "one line of its own.\r\n" ++ "\r\n" ++ // The stuffing is gone and the leading space is the author's. " A line that begins with a space, stuffed so that it survives.\r\n" ++ // The signature separator ends in a space and is not a wrapped // line, so the signature did not get swallowed into the message. "-- \r\n" ++ "Jeff\r\n", text, ); // And the body itself is untouched: `decodeAlloc` is the way to what // arrived, wrap points and all. const raw = try message.root.decodeAlloc(testing.allocator); defer testing.allocator.free(raw); try testing.expect(std.mem.find(u8, raw, "wrapped, and \r\n") != null); } test "a flowed message built here reads back as its paragraphs" { var prng: std.Random.DefaultPrng = .init(0xf10bed); const paragraphs = "Ein Absatz, der lang genug ist, dass er umgebrochen werden muss, " ++ "bevor er in eine Nachricht passt.\n" ++ "\n" ++ "Und ein zweiter, ebenso.\n"; var message: mime.Message = try .init(testing.allocator); defer message.deinit(); try message.root.setSubject("Umbruch"); try message.setText(paragraphs, .{ .format = .flowed }); _ = try message.attach(prng.random(), "a,b\n", .{ .filename = "data.csv" }); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); var read: mime.Message = try .parse(testing.allocator, written, .{}); defer read.deinit(); const plain = read.root.find("text", "plain").?; try testing.expect(plain.media_type.isFlowed()); const text = try plain.textAlloc(testing.allocator); defer testing.allocator.free(text); try testing.expectEqualStrings( "Ein Absatz, der lang genug ist, dass er umgebrochen werden muss, " ++ "bevor er in eine Nachricht passt.\r\n\r\nUnd ein zweiter, ebenso.\r\n", text, ); } const pre_mime = "From: somebody@uunet.uu.net\r\n" ++ "To: jeff@example.com\r\n" ++ "Subject: the picture you asked for\r\n" ++ "Date: Mon, 3 Jan 1994 12:00:00 EST\r\n" ++ "MIME-Version: 1.0\r\n" ++ "Content-Type: multipart/mixed; boundary=\"--\"\r\n" ++ "\r\n" ++ "----\r\n" ++ "Content-Type: text/plain\r\n" ++ "\r\n" ++ "Here it is.\r\n" ++ "----\r\n" ++ "Content-Type: application/octet-stream\r\n" ++ "Content-Transfer-Encoding: X-UUENCODE\r\n" ++ "\r\n" ++ "begin 644 picture.gif\r\n" ++ "&1TE&.#EA\r\n" ++ "`\r\n" ++ "end\r\n" ++ "------\r\n"; test "a message with a uuencoded attachment" { var message = try expectExactRoundTrip(pre_mime); defer message.deinit(); const sent = (try message.root.sentAt()).?; try testing.expectEqual(1994, sent.time.year); try testing.expectEqual(-5 * 60 * 60, sent.time.offset); const file = message.root.find("application", "octet-stream").?; try testing.expectEqual( mime.transfer_encoding.TransferEncoding.uuencode, file.transferEncoding(), ); // The only filename in the whole message is the one on the `begin` line, // which is what a message from before RFC 2183 looks like. try testing.expect(!file.headers.has("content-disposition")); try testing.expectEqual(null, file.media_type.name()); try testing.expectEqualStrings("picture.gif", (try file.filename()).?); try testing.expect(file.isAttachment()); const bytes = try file.decodeAlloc(testing.allocator); defer testing.allocator.free(bytes); try testing.expectEqualStrings("GIF89a", bytes); } const bounce = "From: Mail Delivery System \r\n" ++ "To: jeff@example.com\r\n" ++ "Subject: Undelivered Mail Returned to Sender\r\n" ++ "Date: Tue, 1 Jul 2003 10:52:40 +0200\r\n" ++ "MIME-Version: 1.0\r\n" ++ "Content-Type: multipart/report; report-type=delivery-status;\r\n" ++ "\tboundary=\"3F2A1C0A.mx.example.net\"\r\n" ++ "\r\n" ++ "--3F2A1C0A.mx.example.net\r\n" ++ "Content-Type: text/plain; charset=us-ascii\r\n" ++ "\r\n" ++ "This is the mail system at host mx.example.net.\r\n" ++ "\r\n" ++ "I'm sorry to have to inform you that your message could not\r\n" ++ "be delivered to one or more recipients.\r\n" ++ "\r\n" ++ "--3F2A1C0A.mx.example.net\r\n" ++ "Content-Type: message/delivery-status\r\n" ++ "\r\n" ++ "Reporting-MTA: dns; mx.example.net\r\n" ++ "Arrival-Date: Tue, 1 Jul 2003 10:52:37 +0200\r\n" ++ "\r\n" ++ "Final-Recipient: rfc822; nobody@example.com\r\n" ++ "Action: failed\r\n" ++ "Status: 5.1.1\r\n" ++ "Remote-MTA: dns; mail.example.com\r\n" ++ "Diagnostic-Code: smtp; 550 5.1.1 : Recipient address\r\n" ++ " rejected: User unknown in local recipient table\r\n" ++ "\r\n" ++ "--3F2A1C0A.mx.example.net\r\n" ++ "Content-Type: message/rfc822\r\n" ++ "\r\n" ++ "From: jeff@example.com\r\n" ++ "To: nobody@example.com\r\n" ++ "Subject: Lunch\r\n" ++ "Message-ID: \r\n" ++ "\r\n" ++ "Shall we?\r\n" ++ "--3F2A1C0A.mx.example.net--\r\n"; test "a bounce from a mail system" { var message = try expectExactRoundTrip(bounce); defer message.deinit(); try testing.expect(message.root.media_type.isReport()); try testing.expectEqualStrings("delivery-status", message.root.media_type.reportType().?); const parts = message.root.report().?; try testing.expect(parts.notice.media_type.is("text", "plain")); try testing.expect(parts.machine.?.media_type.is("message", "delivery-status")); try testing.expect(parts.original.?.media_type.is("message", "rfc822")); // The message that failed, which is how a sender finds out *what* bounced. try testing.expectEqualStrings( "original@example.com", parts.original.?.body.message.messageId().?, ); try testing.expectEqualStrings("Lunch", (try parts.original.?.body.message.subject()).?); var status = (try message.root.deliveryStatus(testing.allocator)).?; defer status.deinit(); try testing.expectEqualStrings("mx.example.net", (try status.reportingMta()).?.value); try testing.expectEqual(1, status.recipients.items.len); const recipient = &status.recipients.items[0]; try testing.expectEqual(mime.delivery_status.Action.failed, try recipient.action()); try testing.expectEqualStrings("nobody@example.com", (try recipient.finalRecipient()).?.value); try testing.expect((try recipient.status()).?.isPermanentFailure()); try testing.expect(try status.hasPermanentFailure()); // The diagnostic was folded across two lines and is one value. Postfix // indents its continuation with four spaces, and unfolding keeps them: // a fold removes the line ending and nothing else, because the whitespace // after it is part of the value. try testing.expectEqualStrings( "550 5.1.1 : Recipient address rejected: " ++ "User unknown in local recipient table", (try recipient.diagnosticCode()).?.value, ); } test "a bounce that kept only the headers" { const source = "Content-Type: multipart/report; report-type=delivery-status; boundary=B\r\n" ++ "\r\n" ++ "--B\r\n" ++ "\r\n" ++ "It bounced.\r\n" ++ "--B\r\n" ++ "Content-Type: message/delivery-status\r\n" ++ "\r\n" ++ "Final-Recipient: rfc822; nobody@example.com\r\n" ++ "Action: failed\r\n" ++ "Status: 5.2.2\r\n" ++ "--B\r\n" ++ "Content-Type: text/rfc822-headers\r\n" ++ "\r\n" ++ "From: jeff@example.com\r\n" ++ "Subject: Lunch\r\n" ++ "--B--\r\n"; var message = try expectExactRoundTrip(source); defer message.deinit(); const parts = message.root.report().?; try testing.expect(parts.original.?.media_type.is("text", "rfc822-headers")); var headers = (try parts.original.?.rfc822HeadersAlloc(testing.allocator)).?; defer headers.deinit(); try testing.expectEqualStrings("Lunch", headers.get("subject").?); try testing.expectEqualStrings("jeff@example.com", headers.get("from").?); // Over quota rather than no such user: both permanent, and a program that // prunes a mailing list wants to know which. var status = (try message.root.deliveryStatus(testing.allocator)).?; defer status.deinit(); const found = (try status.recipients.items[0].status()).?; try testing.expectEqual(5, found.class); try testing.expectEqual(2, found.subject); } test "a report whose parts are in the wrong order is still a report" { // The machine-readable part third rather than second, which RFC 6522 does // not allow and which mail systems do anyway. const source = "Content-Type: multipart/report; report-type=delivery-status; boundary=B\r\n" ++ "\r\n" ++ "--B\r\n\r\nIt bounced.\r\n" ++ "--B\r\nContent-Type: message/rfc822\r\n\r\nSubject: Lunch\r\n" ++ "--B\r\nContent-Type: message/delivery-status\r\n\r\n" ++ "Final-Recipient: rfc822; nobody@example.com\r\nAction: failed\r\n" ++ "--B--\r\n"; var message = try expectExactRoundTrip(source); defer message.deinit(); const parts = message.root.report().?; try testing.expect(parts.machine.?.media_type.is("message", "delivery-status")); try testing.expect(parts.original.?.media_type.is("message", "rfc822")); var status = (try message.root.deliveryStatus(testing.allocator)).?; defer status.deinit(); try testing.expectEqual(1, status.recipients.items.len); } test "an ordinary message carries no delivery status" { var message: mime.Message = try .parse( testing.allocator, "Subject: not a bounce\r\n\r\nhello\r\n", .{}, ); defer message.deinit(); try testing.expectEqual(null, message.root.report()); try testing.expectEqual(null, try message.root.deliveryStatus(testing.allocator)); } test "building a bounce" { var prng: std.Random.DefaultPrng = .init(0xb0ce); var failed: mime.Message = try .parse( testing.allocator, "From: jeff@example.com\r\nMessage-ID: \r\n\r\nShall we?\r\n", .{}, ); defer failed.deinit(); var report: mime.Message = try .init(testing.allocator); defer report.deinit(); try report.root.setAddresses("From", &.{ .{ .display_name = "Mail Delivery System", .local_part = "MAILER-DAEMON", .domain = "mx.example.net" }, }); try report.root.setSubject("Undelivered Mail Returned to Sender"); try report.root.makeReportRandom("delivery-status", prng.random()); try report.ensureMimeVersion(); const notice = try report.root.addPart(); try notice.setText("Your message could not be delivered.\n", .{}); var status: mime.delivery_status.DeliveryStatus = .init(testing.allocator); defer status.deinit(); try status.message.append("Reporting-MTA", "dns; mx.example.net"); var recipient: mime.Headers = .init(testing.allocator); errdefer recipient.deinit(); try recipient.append("Final-Recipient", "rfc822; nobody@example.com"); try recipient.append("Action", "failed"); try recipient.append("Status", "5.1.1"); try status.recipients.append(testing.allocator, .{ .fields = recipient }); var body: std.Io.Writer.Allocating = .init(testing.allocator); defer body.deinit(); try status.write(&body.writer); const machine = try report.root.addPart(); try machine.setContentType("message/delivery-status"); machine.body = .{ .raw = try report.allocator().dupe(u8, body.written()) }; const original = try report.root.addPart(); const copied = try report.allocator().create(mime.Message.Part); copied.* = (try mime.Message.parse(report.allocator(), try failed.toBytesAlloc(report.allocator()), .{})).root; try original.setMessage(copied); const written = try report.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); // And it reads back as the bounce it is. var read: mime.Message = try .parse(testing.allocator, written, .{}); defer read.deinit(); try testing.expectEqualStrings("delivery-status", read.root.media_type.reportType().?); var parsed = (try read.root.deliveryStatus(testing.allocator)).?; defer parsed.deinit(); try testing.expect(try parsed.hasPermanentFailure()); try testing.expectEqualStrings( "nobody@example.com", (try parsed.recipients.items[0].finalRecipient()).?.value, ); try testing.expectEqualStrings( "original@example.com", read.root.report().?.original.?.body.message.messageId().?, ); } const receipt = "From: Alice \r\n" ++ "To: jeff@example.com\r\n" ++ "Subject: Read: Lunch\r\n" ++ "MIME-Version: 1.0\r\n" ++ "Content-Type: multipart/report; report-type=disposition-notification;\r\n" ++ "\tboundary=\"R\"\r\n" ++ "\r\n" ++ "--R\r\n" ++ "Content-Type: text/plain\r\n" ++ "\r\n" ++ "Your message was displayed on 1 July 2003.\r\n" ++ "--R\r\n" ++ "Content-Type: message/disposition-notification\r\n" ++ "\r\n" ++ "Reporting-UA: mail.example.net; ExampleMail 4.2\r\n" ++ "Final-Recipient: rfc822; alice@example.net\r\n" ++ "Original-Message-ID: \r\n" ++ "Disposition: manual-action/MDN-sent-manually; displayed\r\n" ++ "--R\r\n" ++ "Content-Type: text/rfc822-headers\r\n" ++ "\r\n" ++ "Subject: Lunch\r\n" ++ "Message-ID: \r\n" ++ "--R--\r\n"; test "a read receipt" { var message = try expectExactRoundTrip(receipt); defer message.deinit(); try testing.expectEqualStrings( "disposition-notification", message.root.media_type.reportType().?, ); // A bounce it is not, and asking for one finds nothing. try testing.expectEqual(null, try message.root.deliveryStatus(testing.allocator)); var found = (try message.root.dispositionNotification(testing.allocator)).?; defer found.deinit(); const disposition = (try found.disposition()).?; try testing.expectEqual(mime.disposition_notification.Type.displayed, disposition.type); // A person chose to send it, which is the most a receipt can claim. try testing.expectEqual(mime.disposition_notification.Mode.manual, disposition.action); try testing.expectEqual(mime.disposition_notification.Mode.manual, disposition.sending); try testing.expectEqualStrings("alice@example.net", (try found.finalRecipient()).?.value); try testing.expectEqualStrings("lunch@example.com", (try found.originalMessageId()).?); try testing.expectEqualStrings("ExampleMail 4.2", (try found.reportingUa()).?.value); } const complaint = "From: Feedback Loop \r\n" ++ "To: abuse@example.com\r\n" ++ "Subject: FW: Great deals inside\r\n" ++ "MIME-Version: 1.0\r\n" ++ "Content-Type: multipart/report; report-type=feedback-report; boundary=\"F\"\r\n" ++ "\r\n" ++ "--F\r\n" ++ "Content-Type: text/plain\r\n" ++ "\r\n" ++ "This is an email abuse report for an email message received from\r\n" ++ "IP 192.0.2.1 on Tue, 1 Jul 2003 10:52:37 +0200.\r\n" ++ "--F\r\n" ++ "Content-Type: message/feedback-report\r\n" ++ "\r\n" ++ "Feedback-Type: abuse\r\n" ++ "User-Agent: SomeGenerator/1.0\r\n" ++ "Version: 1\r\n" ++ "Original-Mail-From: \r\n" ++ "Arrival-Date: Tue, 1 Jul 2003 10:52:37 +0200\r\n" ++ "Source-IP: 192.0.2.1\r\n" ++ "Reported-Domain: example.com\r\n" ++ "--F\r\n" ++ "Content-Type: message/rfc822\r\n" ++ "\r\n" ++ "From: newsletter@example.com\r\n" ++ "To: someone@example.net\r\n" ++ "Subject: Great deals inside\r\n" ++ "\r\n" ++ "Buy things.\r\n" ++ "--F--\r\n"; test "a spam complaint" { var message = try expectExactRoundTrip(complaint); defer message.deinit(); try testing.expectEqualStrings("feedback-report", message.root.media_type.reportType().?); var found = (try message.root.feedbackReport(testing.allocator)).?; defer found.deinit(); try testing.expectEqual(mime.feedback_report.Type.abuse, try found.feedbackType()); try testing.expectEqual(1, (try found.version()).?); try testing.expectEqualStrings("192.0.2.1", (try found.sourceIp()).?); // The envelope sender, which is how a sender finds the subscription that // generated the complaint... try testing.expectEqualStrings("", (try found.originalMailFrom()).?); // ...because the complainant's own address is redacted, which is what // RFC 6590 asks of providers and is the normal case. try testing.expectEqual(null, try found.originalRcptTo()); // And the message complained about is the third part, where a sender // finds its own tracking identifier instead. const original = message.root.report().?.original.?; try testing.expect(original.media_type.is("message", "rfc822")); try testing.expectEqualStrings( "Great deals inside", (try original.body.message.subject()).?, ); } test "a mailto link becomes a message that can be sent" { var prng: std.Random.DefaultPrng = .init(0xa11e); var message = try mime.mailto.parse( testing.allocator, "mailto:alice@example.net?subject=Gr%C3%BC%C3%9Fe&body=Sch%C3%B6ne%20Gr%C3%BC%C3%9Fe.", .{}, ); defer message.deinit(); // What a composer would do next: name the sender, date it, identify it, // and attach something. try message.root.setAddresses("From", &.{ .{ .display_name = "Jeff Ollie", .local_part = "jeff", .domain = "example.com" }, }); try message.root.setMessageId("example.com", prng.random()); _ = try message.attach(prng.random(), "a,b\n", .{ .filename = "data.csv" }); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); var read: mime.Message = try .parse(testing.allocator, written, .{}); defer read.deinit(); try testing.expectEqualStrings("Grüße", (try read.root.subject()).?); const text = read.root.findText(&.{ "plain", "html" }).?; const body = try text.textAlloc(testing.allocator); defer testing.allocator.free(body); try testing.expectEqualStrings("Schöne Grüße.", body); var attachments = read.root.attachments(); try testing.expectEqualStrings("data.csv", (try attachments.next().?.filename()).?); try testing.expectEqual(null, attachments.next()); }