Something went wrong. Try again.
Reading, writing and creating MIME and RFC 5322 email messages in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! `message/delivery-status` — RFC 3464 — which is the part of a bounce that//! says what actually happened.//!//! A delivery status notification arrives as a `multipart/report` of two or//! three parts: a human-readable apology, this, and usually the message that//! failed. The apology is the part everybody reads and the part nobody can//! parse — every mail system words it differently, and half of them word it//! badly. This is the other one: the same information, in a format a program//! can act on.//!//! ```text//! Reporting-MTA: dns; mx.example.net//! Arrival-Date: Tue, 1 Jul 2003 10:52:37 +0200//!//! Final-Recipient: rfc822; nobody@example.com//! Action: failed//! Status: 5.1.1//! Diagnostic-Code: smtp; 550 5.1.1 <nobody@example.com>: User unknown//! ```//!//! The body is *header syntax*, which is the whole trick of the format: groups//! of `Name: value` separated by blank lines, folded the same way, and parsed//! by the same code. The first group is about the delivery attempt and the//! ones after it are about one recipient each — a message to five addresses//! that failed for three of them bounces once, with three recipient groups.//!//! Two fields carry the answer. **`Action`** says what happened in one word,//! and only `failed` is permanent. **`Status`** is an RFC 3463 enhanced status//! code — `5.1.1`, three numbers separated by full stops — whose first number//! is the one that matters: 2 succeeded, 4 is temporary and will be retried,//! 5 is permanent. A program deciding whether to stop mailing an address//! should read the class and not the prose, because `Diagnostic-Code` is a//! remote server's own words and says whatever that server's author felt like.
const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;const testing = std.testing;
const Headers = @import("Headers.zig");const date = @import("header/date.zig");const reports = @import("report.zig");
/// `type; value`, which every kind of report writes its fields as. Here for/// the caller that reached this module first.pub const TypedValue = reports.TypedValue;
/// What happened to the message for one recipient. RFC 3464 §2.3.3.pub const Action = enum { /// Permanently undeliverable. The only value that means stop trying. failed, /// Not delivered yet, still being retried. A later report will say how it /// ended; this one is a warning, and a great many of them are sent after /// four hours and resolved by themselves. delayed, /// Delivered, reported because the sender asked for a receipt. delivered, /// Passed to a system that does not support delivery reports, so this is /// the last that will be heard of it either way. relayed, /// The address was a list or an alias and the message went to its /// members, whose own reports will arrive separately. expanded, /// Something else was written. RFC 3464 defines five values and the field /// is not extensible, so this means the report is malformed. other,
pub fn parse(text: []const u8) Action { const trimmed = std.mem.trim(u8, text, " \t\r\n"); const table = .{ .{ "failed", Action.failed }, .{ "delayed", Action.delayed }, .{ "delivered", Action.delivered }, .{ "relayed", Action.relayed }, .{ "expanded", Action.expanded }, }; inline for (table) |entry| { if (std.ascii.eqlIgnoreCase(trimmed, entry[0])) return entry[1]; } return .other; }
pub fn name(self: Action) []const u8 { return switch (self) { .failed => "failed", .delayed => "delayed", .delivered => "delivered", .relayed => "relayed", .expanded => "expanded", .other => "failed", }; }};
/// An RFC 3463 enhanced status code: `class.subject.detail`.////// The class is the part worth reading. The subject and detail are a/// taxonomy that mail systems fill in with varying enthusiasm, and a program/// that switches on `5.1.1` rather than on `5` will be surprised by the server/// that says `5.0.0` and means the same thing.pub const Status = struct { /// 2 for success, 4 for a temporary failure, 5 for a permanent one. class: u8, subject: u16, detail: u16,
pub fn parse(text: []const u8) ?Status { const trimmed = std.mem.trim(u8, text, " \t\r\n"); var parts = std.mem.splitScalar(u8, trimmed, '.'); const class = number(parts.next() orelse return null) orelse return null; const subject = number(parts.next() orelse return null) orelse return null; const detail = number(parts.next() orelse return null) orelse return null; if (parts.next() != null) return null; if (class > 255 or subject > 999 or detail > 999) return null; return .{ .class = @intCast(class), .subject = @intCast(subject), .detail = @intCast(detail), }; }
fn number(text: []const u8) ?u32 { if (text.len == 0 or text.len > 3) return null; for (text) |c| if (!std.ascii.isDigit(c)) return null; return std.fmt.parseInt(u32, text, 10) catch null; }
/// Whether the message will not be delivered and retrying will not help. pub fn isPermanentFailure(self: Status) bool { return self.class == 5; }
/// Whether the failure is expected to resolve itself. The sending system /// is still trying; a report saying this is a warning rather than a /// bounce. pub fn isTransientFailure(self: Status) bool { return self.class == 4; }
pub fn isSuccess(self: Status) bool { return self.class == 2; }
pub fn format(self: Status, w: *Io.Writer) Io.Writer.Error!void { return w.print("{d}.{d}.{d}", .{ self.class, self.subject, self.detail }); }};
/// What happened to one recipient.pub const Recipient = struct { /// Every field of the group, so that anything not named below — and a /// report may carry extension fields — is still reachable. fields: Headers,
/// The address the report is about, as the reporting system finally had /// it. RFC 3464 requires this field; a report without one is about /// nobody. pub fn finalRecipient(self: *Recipient) Allocator.Error!?TypedValue { return self.typed("final-recipient"); }
/// The address as the *sender* wrote it, before any alias or list /// expansion. This is the one to match against what was sent, and it is /// frequently missing. pub fn originalRecipient(self: *Recipient) Allocator.Error!?TypedValue { return self.typed("original-recipient"); }
pub fn action(self: *Recipient) Allocator.Error!Action { const value = try self.fields.getUnfolded("action") orelse return .other; return Action.parse(value); }
pub fn status(self: *Recipient) Allocator.Error!?Status { const value = try self.fields.getUnfolded("status") orelse return null; return Status.parse(value); }
/// The system that refused it. pub fn remoteMta(self: *Recipient) Allocator.Error!?TypedValue { return self.typed("remote-mta"); }
/// What the refusing system said, in its own words — usually the SMTP /// reply, often several lines of it folded into one field. Worth showing /// a person and not worth deciding anything on. pub fn diagnosticCode(self: *Recipient) Allocator.Error!?TypedValue { return self.typed("diagnostic-code"); }
pub fn lastAttempt(self: *Recipient) Allocator.Error!?date.Parsed { const value = try self.fields.getUnfolded("last-attempt-date") orelse return null; return date.parse(value) catch null; }
/// When the sending system will give up, for a `delayed` report. pub fn willRetryUntil(self: *Recipient) Allocator.Error!?date.Parsed { const value = try self.fields.getUnfolded("will-retry-until") orelse return null; return date.parse(value) catch null; }
fn typed(self: *Recipient, name: []const u8) Allocator.Error!?TypedValue { const value = try self.fields.getUnfolded(name) orelse return null; return TypedValue.parse(value); }};
/// A parsed `message/delivery-status` body.pub const DeliveryStatus = struct { gpa: Allocator, /// The fields about the delivery attempt as a whole: `Reporting-MTA`, /// `Arrival-Date`, and whatever else the reporting system added. message: Headers, recipients: std.ArrayList(Recipient) = .empty,
pub fn init(gpa: Allocator) DeliveryStatus { return .{ .gpa = gpa, .message = .init(gpa) }; }
pub fn deinit(self: *DeliveryStatus) void { self.message.deinit(); for (self.recipients.items) |*recipient| recipient.fields.deinit(); self.recipients.deinit(self.gpa); self.* = undefined; }
/// Parses the body of a `message/delivery-status` part. /// /// Never fails except on allocation. A bounce is a message about a /// message that already went wrong, and refusing to read it because a /// field is malformed leaves the caller with nothing at all — the /// accessors return null for what is missing, and `Action.other` for what /// makes no sense. pub fn parse(gpa: Allocator, body: []const u8) Allocator.Error!DeliveryStatus { var self: DeliveryStatus = .init(gpa); errdefer self.deinit();
var groups: reports.GroupIterator = .init(body); var first = true; while (groups.next()) |group| { var fields: Headers = try .parse(gpa, group); errdefer fields.deinit();
// A group that holds no field at all is not a recipient. Some // reporting systems put a line of prose or a separator between // the groups, and reading one as a recipient invents an entry // that names nobody, reports `Action.other`, and is counted by // anything walking the list to say which addresses bounced. // Skipping it also keeps the per-message group in the right // place: a report whose first line is prose would otherwise // spend the per-message slot on it and read the real // `Reporting-MTA` group as a recipient. if (fields.fields.items.len == 0) { fields.deinit(); continue; }
// The per-message group comes first. A report that begins with // recipient fields is malformed and is read as though the // per-message group had been empty, which loses nothing: the // recipient is what the caller came for. if (first and !fields.has("final-recipient") and !fields.has("action")) { self.message.deinit(); self.message = fields; first = false; continue; } first = false; try self.recipients.append(gpa, .{ .fields = fields }); } return self; }
/// The system that generated the report. pub fn reportingMta(self: *DeliveryStatus) Allocator.Error!?TypedValue { const value = try self.message.getUnfolded("reporting-mta") orelse return null; return TypedValue.parse(value); }
/// When the message being reported on arrived at the reporting system. pub fn arrivalDate(self: *DeliveryStatus) Allocator.Error!?date.Parsed { const value = try self.message.getUnfolded("arrival-date") orelse return null; return date.parse(value) catch null; }
/// Whether any recipient failed permanently — the question a program /// processing bounces is usually asking. pub fn hasPermanentFailure(self: *DeliveryStatus) Allocator.Error!bool { for (self.recipients.items) |*recipient| { if (try recipient.action() != .failed) continue; const found = try recipient.status() orelse return true; if (found.isPermanentFailure()) return true; } return false; }
/// Writes the body back out: the per-message group, a blank line, and each /// recipient group after it. pub fn write(self: DeliveryStatus, w: *Io.Writer) Io.Writer.Error!void { try self.message.writeFields(w); for (self.recipients.items) |recipient| { try w.writeAll("\r\n"); try recipient.fields.writeFields(w); } }
pub fn format(self: DeliveryStatus, w: *Io.Writer) Io.Writer.Error!void { return self.write(w); }};
const example = "Reporting-MTA: dns; mx.example.net\r\n" ++ "Arrival-Date: Tue, 1 Jul 2003 10:52:37 +0200\r\n" ++ "\r\n" ++ "Original-Recipient: rfc822; everyone@example.com\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 <nobody@example.com>: User unknown\r\n" ++ "\r\n" ++ "Final-Recipient: rfc822; busy@example.com\r\n" ++ "Action: delayed\r\n" ++ "Status: 4.2.2\r\n" ++ "Will-Retry-Until: Fri, 4 Jul 2003 10:52:37 +0200\r\n";
test "a report about two recipients" { var report: DeliveryStatus = try .parse(testing.allocator, example); defer report.deinit();
const mta = (try report.reportingMta()).?; try testing.expectEqualStrings("dns", mta.type); try testing.expectEqualStrings("mx.example.net", mta.value); try testing.expectEqual(2003, (try report.arrivalDate()).?.time.year);
try testing.expectEqual(2, report.recipients.items.len);
const failed = &report.recipients.items[0]; try testing.expectEqual(Action.failed, try failed.action()); try testing.expectEqualStrings("nobody@example.com", (try failed.finalRecipient()).?.value); try testing.expectEqualStrings("everyone@example.com", (try failed.originalRecipient()).?.value); try testing.expectEqualStrings("rfc822", (try failed.finalRecipient()).?.type); try testing.expectEqualStrings("mail.example.com", (try failed.remoteMta()).?.value);
const status = (try failed.status()).?; try testing.expectEqual(5, status.class); try testing.expectEqual(1, status.subject); try testing.expectEqual(1, status.detail); try testing.expect(status.isPermanentFailure());
const diagnostic = (try failed.diagnosticCode()).?; try testing.expectEqualStrings("smtp", diagnostic.type); try testing.expectEqualStrings("550 5.1.1 <nobody@example.com>: User unknown", diagnostic.value);
const delayed = &report.recipients.items[1]; try testing.expectEqual(Action.delayed, try delayed.action()); try testing.expect((try delayed.status()).?.isTransientFailure()); try testing.expectEqual(2003, (try delayed.willRetryUntil()).?.time.year); try testing.expectEqual(null, try delayed.remoteMta());
try testing.expect(try report.hasPermanentFailure());}
test "a folded diagnostic is one value" { const body = "Reporting-MTA: dns; mx.example.net\r\n" ++ "\r\n" ++ "Final-Recipient: rfc822; nobody@example.com\r\n" ++ "Action: failed\r\n" ++ "Status: 5.7.1\r\n" ++ "Diagnostic-Code: smtp; 550-5.7.1 This message does not have\r\n" ++ " authentication information or fails to pass\r\n" ++ " authentication checks.\r\n"; var report: DeliveryStatus = try .parse(testing.allocator, body); defer report.deinit();
try testing.expectEqual(1, report.recipients.items.len); const diagnostic = (try report.recipients.items[0].diagnosticCode()).?; try testing.expectEqualStrings( "550-5.7.1 This message does not have authentication information " ++ "or fails to pass authentication checks.", diagnostic.value, );}
test "a delayed report is not a permanent failure" { const body = "Reporting-MTA: dns; mx.example.net\r\n\r\n" ++ "Final-Recipient: rfc822; busy@example.com\r\nAction: delayed\r\nStatus: 4.4.1\r\n"; var report: DeliveryStatus = try .parse(testing.allocator, body); defer report.deinit(); try testing.expect(!try report.hasPermanentFailure());}
test "a report that begins with its recipient" { // Malformed -- the per-message group is required -- and the recipient is // what the caller came for either way. const body = "Final-Recipient: rfc822; nobody@example.com\r\nAction: failed\r\n"; var report: DeliveryStatus = try .parse(testing.allocator, body); defer report.deinit(); try testing.expectEqual(1, report.recipients.items.len); try testing.expectEqual(0, report.message.fields.items.len); try testing.expectEqual(null, try report.reportingMta());}
test "nothing at all" { var report: DeliveryStatus = try .parse(testing.allocator, ""); defer report.deinit(); try testing.expectEqual(0, report.recipients.items.len); try testing.expect(!try report.hasPermanentFailure());}
test "a report written back out is the report" { var report: DeliveryStatus = try .parse(testing.allocator, example); defer report.deinit();
var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try report.write(&out.writer); try testing.expectEqualStrings(example, out.written());}
test "a report built by hand" { var report: DeliveryStatus = .init(testing.allocator); defer report.deinit(); try report.message.append("Reporting-MTA", "dns; mx.example.net");
var recipient: 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 report.recipients.append(testing.allocator, .{ .fields = recipient });
var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try report.write(&out.writer); try testing.expectEqualStrings( "Reporting-MTA: dns; mx.example.net\r\n" ++ "\r\n" ++ "Final-Recipient: rfc822; nobody@example.com\r\n" ++ "Action: failed\r\n" ++ "Status: 5.1.1\r\n", out.written(), );}
test Status { try testing.expectEqual(null, Status.parse("")); try testing.expectEqual(null, Status.parse("5.1")); try testing.expectEqual(null, Status.parse("5.1.1.1")); try testing.expectEqual(null, Status.parse("five.one.one")); try testing.expectEqual(null, Status.parse("5.1.1000"));
const status = Status.parse(" 4.2.2 ").?; try testing.expect(status.isTransientFailure()); try testing.expect(!status.isPermanentFailure()); try testing.expect(!status.isSuccess());
var buffer: [16]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try w.print("{f}", .{status}); try testing.expectEqualStrings("4.2.2", w.buffered());}
test Action { try testing.expectEqual(Action.failed, Action.parse("Failed")); try testing.expectEqual(Action.delayed, Action.parse(" delayed ")); try testing.expectEqual(Action.other, Action.parse("bounced")); try testing.expectEqual(Action.other, Action.parse(""));}