Something went wrong. Try again.
Reading, writing and creating MIME and RFC 5322 email messages in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! `mailto:` URLs — RFC 6068 — turned into a message, and back.//!//! ```text//! mailto:alice@example.net,bob@example.org?subject=Lunch&body=Shall%20we%3F//! ```//!//! Everything after the `?` is a list of header fields, percent-encoded, with//! one name that is not a header: `body`, which is the text of the message.//! The addresses before the `?` are recipients, and any `to` field in the//! query is added to them rather than replacing them.//!//! Two details that are got wrong more often than they are got right://!//! * **`+` is not a space.** That rule belongs to HTML form encoding, and a//! `mailto:` is a URI: a space is `%20` and a `+` is a plus sign, which is//! a character that appears in a great many real addresses. Converting it//! silently mails somebody else.//! * **The header list is not open.** A `mailto:` arrives from a web page or//! another message — it is attacker-supplied by construction — and one that//! sets `From` is a forged sender, one that sets `Content-Type` can make a//! reader display something other than what the URL appears to say. RFC 6068//! §6.1 asks clients to restrict what a URL may set, and `Options.allowed`//! is that restriction. It defaults to the fields a link plausibly needs and//! nothing else; widening it is a decision, which is why it has to be made//! in the caller rather than here.
const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;const testing = std.testing;
const uri = @import("uri");
const Message = @import("Message.zig");const address = @import("header/address.zig");
pub const Error = error{ /// The text does not begin `mailto:`. NotMailto,};
/// The header fields a URL may set by default: the ones a link plausibly/// needs.////// `from`, `reply-to` and `sender` are deliberately absent — a URL that sets/// them is claiming to be somebody — and so is everything beginning/// `content-`, which decides how the message is displayed.pub const safe_headers = [_][]const u8{ "to", "cc", "bcc", "subject", "in-reply-to", "references", "keywords", "comments",};
pub const Options = struct { /// Which header fields the URL is allowed to set, compared /// case-insensitively. Anything else in the query is ignored. allowed: []const []const u8 = &safe_headers, /// The charset declared on the body. As everywhere else here this does not /// transcode: RFC 6068 says a `mailto:` is UTF-8, and so is this. charset: []const u8 = "UTF-8",};
/// Builds a message from a `mailto:` URL. The caller owns it.pub fn parse(gpa: Allocator, url: []const u8, options: Options) (Error || Allocator.Error)!Message { if (!std.ascii.startsWithIgnoreCase(url, "mailto:")) return error.NotMailto; const rest = url["mailto:".len..];
var message: Message = try .init(gpa); errdefer message.deinit(); const a = message.allocator();
const question = std.mem.findScalar(u8, rest, '?'); const path = rest[0 .. question orelse rest.len]; const query = if (question) |at| rest[at + 1 ..] else "";
// Recipients from the path, and from any `to` in the query, joined. var recipients: Io.Writer.Allocating = .init(a); try appendDecoded(a, &recipients, path);
var body: ?[]const u8 = null;
var fields = std.mem.splitScalar(u8, query, '&'); while (fields.next()) |pair| { if (pair.len == 0) continue; const equals = std.mem.findScalar(u8, pair, '=') orelse continue; const name = try decode(a, pair[0..equals]); const value = try decode(a, pair[equals + 1 ..]);
if (std.ascii.eqlIgnoreCase(name, "body")) { body = value; continue; } if (std.ascii.eqlIgnoreCase(name, "to")) { try appendJoined(a, &recipients, value); continue; } if (!isAllowed(name, options.allowed)) continue; try setHeader(&message, name, value); }
if (recipients.written().len != 0) { try setHeader(&message, "To", recipients.written()); } try message.setText(body orelse "", .{ .charset = options.charset }); return message;}
/// Sets one header, encoding it the way that header needs.////// An address list goes through the address writer, so that a display name/// with a comma or an accent in it produces a header that means what the URL/// said; everything else goes through the encoded-word writer. Neither is/// optional: the values come out of a URL and may be anything.fn setHeader(message: *Message, name: []const u8, value: []const u8) Allocator.Error!void { const gpa = message.allocator(); if (std.ascii.eqlIgnoreCase(name, "to") or std.ascii.eqlIgnoreCase(name, "cc") or std.ascii.eqlIgnoreCase(name, "bcc")) { var list: address.List = try .parse(gpa, value); defer list.deinit(gpa); var out: Io.Writer.Allocating = .init(gpa); list.write(&out.writer) catch return error.OutOfMemory; try message.root.headers.set(canonicalName(name), out.written()); return; } return message.root.setTextHeader(canonicalName(name), value);}
/// The spelling to write a known header under, so that a URL saying `SUBJECT`/// does not produce one.fn canonicalName(name: []const u8) []const u8 { const known = [_][]const u8{ "To", "Cc", "Bcc", "Subject", "In-Reply-To", "References", "Keywords", "Comments", }; for (known) |candidate| { if (std.ascii.eqlIgnoreCase(name, candidate)) return candidate; } return name;}
fn isAllowed(name: []const u8, allowed: []const []const u8) bool { for (allowed) |candidate| { if (std.ascii.eqlIgnoreCase(name, candidate)) return true; } return false;}
fn decode(a: Allocator, text: []const u8) Allocator.Error![]const u8 { // Lenient: a `%` that is not an escape is a `%`. These arrive from web // pages, and refusing one for a stray percent sign helps nobody. return uri.percent.decode(a, text, false) catch |err| switch (err) { error.OutOfMemory => error.OutOfMemory, else => a.dupe(u8, text), };}
fn appendDecoded(a: Allocator, out: *Io.Writer.Allocating, text: []const u8) Allocator.Error!void { if (text.len == 0) return; return appendJoined(a, out, try decode(a, text));}
fn appendJoined(a: Allocator, out: *Io.Writer.Allocating, text: []const u8) Allocator.Error!void { _ = a; if (text.len == 0) return; if (out.written().len != 0) out.writer.writeAll(", ") catch return error.OutOfMemory; out.writer.writeAll(text) catch return error.OutOfMemory;}
/// What a `mailto:` link is made of, for writing one.pub const Fields = struct { /// Comma-separated, and written into the URL before the `?`. to: []const u8 = "", cc: []const u8 = "", bcc: []const u8 = "", subject: []const u8 = "", body: []const u8 = "",};
/// Writes a `mailto:` URL.////// Everything is percent-encoded, including the characters that are only/// dangerous in a URL rather than in a header: a `&` in a subject would/// otherwise start a field of its own, and a `?` would start the query twice.pub fn writeUrl(w: *Io.Writer, fields: Fields) Io.Writer.Error!void { try w.writeAll("mailto:"); try uri.percent.encode(w, fields.to, &address_safe);
var written: usize = 0; inline for (.{ .{ "cc", fields.cc }, .{ "bcc", fields.bcc }, .{ "subject", fields.subject }, .{ "body", fields.body }, }) |pair| { if (pair[1].len != 0) { try w.writeByte(if (written == 0) '?' else '&'); try w.writeAll(pair[0]); try w.writeByte('='); try uri.percent.encode(w, pair[1], &value_safe); written += 1; } }}
pub fn writeUrlAlloc(gpa: Allocator, fields: Fields) Allocator.Error![]u8 { var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); writeUrl(&out.writer, fields) catch return error.OutOfMemory; return out.toOwnedSlice();}
/// What may go unescaped in the address part. Not `&`, `=`, `?`, `%` or `#`,/// each of which means something to the URL rather than to the address.const address_safe = uri.percent.charSet(.{ .add = "-._~!$'()*+,;:@" });
/// The same, plus `/`, which is common in a body and harmless in a query.const value_safe = uri.percent.charSet(.{ .add = "-._~!$'()*+,;:@/" });
test "the ordinary link" { var message = try parse( testing.allocator, "mailto:alice@example.net?subject=Lunch&body=Shall%20we%3F", .{}, ); defer message.deinit();
try testing.expectEqualStrings("alice@example.net", message.root.headers.get("to").?); try testing.expectEqualStrings("Lunch", (try message.root.subject()).?);
// Exactly what the URL said: no line ending was asked for and none is // invented. const body = try message.root.textAlloc(testing.allocator); defer testing.allocator.free(body); try testing.expectEqualStrings("Shall we?", body);}
test "recipients from the path and the query are joined" { var message = try parse( testing.allocator, "mailto:alice@example.net,bob@example.org?to=carol@example.com&cc=dave@example.net", .{}, ); defer message.deinit();
var to = try message.root.addresses(testing.allocator, "to"); defer to.deinit(testing.allocator); try testing.expectEqual(3, to.addresses.len); try testing.expectEqualStrings("alice", to.addresses[0].mailbox.local_part); try testing.expectEqualStrings("carol", to.addresses[2].mailbox.local_part); try testing.expectEqualStrings("dave@example.net", message.root.headers.get("cc").?);}
test "a plus sign is a plus sign" { // The rule that belongs to form encoding and not to this one. A `+` in an // address is a character, and turning it into a space mails somebody else. var message = try parse(testing.allocator, "mailto:jeff%2Blists@example.com", .{}); defer message.deinit(); try testing.expectEqualStrings("jeff+lists@example.com", message.root.headers.get("to").?);
var literal = try parse(testing.allocator, "mailto:jeff+lists@example.com", .{}); defer literal.deinit(); try testing.expectEqualStrings("jeff+lists@example.com", literal.root.headers.get("to").?);}
test "a URL cannot forge a sender" { var message = try parse( testing.allocator, "mailto:alice@example.net?from=bank@example.com&reply-to=thief@evil.test" ++ "&content-type=text/html&subject=Your%20account", .{}, ); defer message.deinit();
try testing.expect(!message.root.headers.has("from")); try testing.expect(!message.root.headers.has("reply-to")); // And the Content-Type is the one this library wrote, not the one asked // for. try testing.expect(message.root.media_type.is("text", "plain")); try testing.expectEqualStrings("Your account", (try message.root.subject()).?);}
test "what a caller may allow instead" { var message = try parse( testing.allocator, "mailto:alice@example.net?reply-to=list@example.org", .{ .allowed = &.{ "to", "reply-to" } }, ); defer message.deinit(); try testing.expectEqualStrings("list@example.org", message.root.headers.get("reply-to").?);}
test "a subject that is not ASCII" { var message = try parse( testing.allocator, "mailto:alice@example.net?subject=Gr%C3%BC%C3%9Fe%20aus%20M%C3%BCnchen", .{}, ); defer message.deinit(); try testing.expectEqualStrings("Grüße aus München", (try message.root.subject()).?);
// And the header that was written is ASCII, as a header must be. const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); for (written) |c| try testing.expect(c < 0x80);}
test "a display name with a comma in it" { var message = try parse( testing.allocator, "mailto:%22Ollie%2C%20Jeff%22%20%3Cjeff@example.com%3E", .{}, ); defer message.deinit();
var to = try message.root.addresses(testing.allocator, "to"); defer to.deinit(testing.allocator); try testing.expectEqual(1, to.addresses.len); try testing.expectEqualStrings("Ollie, Jeff", to.addresses[0].mailbox.display_name.?);}
test "the shapes that are not links" { try testing.expectError(error.NotMailto, parse(testing.allocator, "https://example.com", .{})); try testing.expectError(error.NotMailto, parse(testing.allocator, "", .{}));
// A link with no recipient is a link all the same: "compose to nobody". var empty = try parse(testing.allocator, "mailto:?subject=Hello", .{}); defer empty.deinit(); try testing.expect(!empty.root.headers.has("to")); try testing.expectEqualStrings("Hello", (try empty.root.subject()).?);}
test "writing a link" { const url = try writeUrlAlloc(testing.allocator, .{ .to = "alice@example.net", .subject = "Lunch & other business", .body = "Shall we? 100% sure", }); defer testing.allocator.free(url); try testing.expectEqualStrings( "mailto:alice@example.net?subject=Lunch%20%26%20other%20business" ++ "&body=Shall%20we%3F%20100%25%20sure", url, );
// And it reads back as what went in, which is what the escaping is for. var message = try parse(testing.allocator, url, .{}); defer message.deinit(); try testing.expectEqualStrings("Lunch & other business", (try message.root.subject()).?); const body = try message.root.textAlloc(testing.allocator); defer testing.allocator.free(body); try testing.expectEqualStrings("Shall we? 100% sure", body);}