// An Internet message as RFC 5322 and MIME make of it (its header fields, its text and HTML, its attachments), read // from the bytes a mail server took: the one reader the mail twins share (a receiving server's mailbox, a sending API's // SMTP lane). Pure and side-effect-free; multipart bodies are framed by the kernel's one multipart reader. import { multipartBoundary, multipartEnvelope } from './multipart.ts'; export type MailAttachment = { filename: string | null; contentType: string; disposition: 'attachment' | 'inline'; contentId: string | null; bytes: Uint8Array }; export type MailMessage = { headers: Record; text: string | null; html: string | null; attachments: MailAttachment[] }; type Part = { headers: Record; body: Uint8Array }; const bytesOf = (s: string): Uint8Array => Uint8Array.from(s, (c) => c.charCodeAt(0) & 0xff); const binary = (b: Uint8Array): string => { let s = ''; for (const c of b) s += String.fromCharCode(c); return s; }; const utf8 = (b: Uint8Array): string => new TextDecoder().decode(b); const textFor = (b: Uint8Array, charset: string | undefined): string => { try { return new TextDecoder(charset ?? 'utf-8').decode(b); } catch { return utf8(b); } }; /** Header fields, folded lines unfolded and names lowercased, a repeated field's first value kept (RFC 5322 §2.2.3). */ // source: https://www.rfc-editor.org/rfc/rfc5322 "Unfolding is accomplished by simply removing any CRLF that is immediately followed by WSP" function fields(head: Uint8Array): Record { const out: Record = {}; for (const line of utf8(head).replace(/\r?\n[ \t]+/g, ' ').split(/\r?\n/)) { const i = line.indexOf(':'); if (i > 0) out[line.slice(0, i).trim().toLowerCase()] ??= line.slice(i + 1).trim(); } return out; } /** Header and body split at the first empty line. */ function split(raw: Uint8Array): Part { const text = binary(raw); const at = text.search(/\r?\n\r?\n/); if (at < 0) return { headers: fields(raw), body: new Uint8Array() }; const gap = /^\r?\n\r?\n/.exec(text.slice(at))![0].length; return { headers: fields(raw.subarray(0, at)), body: raw.subarray(at + gap) }; } /** A field's parameter (`; name="value"`, RFC 2231's `name*=utf-8''…` decoded). */ function mailParam(value: string, name: string): string | undefined { const m = new RegExp(`;\\s*${name}\\*?=\\s*(?:"([^"]*)"|([^;\\s]+))`, 'i').exec(value); const v = m?.[1] ?? m?.[2]; return v?.startsWith("utf-8''") || v?.startsWith("UTF-8''") ? decodeURIComponent(v.slice(7)) : v; } /** A part's body decoded by its Content-Transfer-Encoding: base64 and quoted-printable to bytes (RFC 2045 §6). */ function decoded(part: Part): Uint8Array { const enc = (part.headers['content-transfer-encoding'] ?? '7bit').toLowerCase(); const body = binary(part.body); if (enc === 'base64') { try { return bytesOf(atob(body.replace(/\s+/g, ''))); } catch { return part.body; } } if (enc === 'quoted-printable') return bytesOf(body.replace(/=\r?\n/g, '').replace(/=([0-9A-Fa-f]{2})/g, (_, h: string) => String.fromCharCode(Number.parseInt(h, 16)))); return part.body; } /** Encoded words in a header (`=?UTF-8?B?…?=`, `=?UTF-8?Q?…?=`), decoded (RFC 2047). */ // source: https://www.rfc-editor.org/rfc/rfc2047 "encoded-word = \"=?\" charset \"?\" encoding \"?\" encoded-text \"?=\"" export function mailWords(value: string): string { return value.replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=(\s+(?==\?))?/g, (_, cs: string, e: string, t: string) => { try { return textFor(e.toUpperCase() === 'B' ? bytesOf(atob(t)) : bytesOf(t.replace(/_/g, ' ').replace(/=([0-9A-Fa-f]{2})/g, (_m, h: string) => String.fromCharCode(Number.parseInt(h, 16)))), cs); } catch { return t; } }); } /** An address list's members as written (`Name ` or `a@b`), its encoded words decoded, split at the commas * outside quotes. */ export const mailAddressList = (v: string | undefined): string[] => (v ? mailWords(v).split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/).map((a) => a.trim()).filter(Boolean) : []); /** The message's leaves: a multipart's parts (recursively), else the one. */ function leaves(part: Part): Part[] { const boundary = multipartBoundary(part.headers['content-type']); if (!boundary) return [part]; return multipartEnvelope(part.body, boundary).parts.flatMap((p) => leaves({ headers: fields(p.headers), body: p.body })); } /** A message from the bytes a server took (a binary string, one character per byte): the first text/plain and text/html * leaves that are not attachments are its text and HTML, every other leaf an attachment. */ export function readMailMessage(data: string): MailMessage { const top = split(bytesOf(data)); let text: string | null = null; let html: string | null = null; const attachments: MailAttachment[] = []; for (const leaf of leaves(top)) { const contentType = leaf.headers['content-type'] ?? 'text/plain'; const type = contentType.split(';')[0]!.trim().toLowerCase(); const disposition = leaf.headers['content-disposition'] ?? ''; const filename = mailParam(disposition, 'filename') ?? mailParam(contentType, 'name'); const bytes = decoded(leaf); if (!/^attachment/i.test(disposition) && !filename && type === 'text/plain' && text === null) { text = textFor(bytes, mailParam(contentType, 'charset')); continue; } if (!/^attachment/i.test(disposition) && !filename && type === 'text/html' && html === null) { html = textFor(bytes, mailParam(contentType, 'charset')); continue; } attachments.push({ filename: filename ? mailWords(filename) : null, contentType: type, disposition: /^inline/i.test(disposition) ? 'inline' : 'attachment', contentId: leaf.headers['content-id']?.replace(/^<|>$/g, '') ?? null, bytes }); } return { headers: top.headers, text, html, attachments }; }