Watch
1
0
Fork
You've already forked packages
0
packages/email/mime.weft
Weft packages 306b143104 packages/ at markup-kit dd1e6eb5270e
A snapshot of packages/ in the Weft repository; the official packages are published from these commits.

Markup-Kit-Commit: dd1e6eb5270e62e0c8b6c202b3d01f0da6e00ddc
2026-11-19 20:43:26 +00:00

208 lines
6.6 KiB
Text
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// MIME: a message as the text mail servers exchange (RFC 5322, RFC 2045–2047, RFC 2231).
import { uuid } from "std/random"
import { emailOf, nameOf } from "./email"
import type { Address, Attachment, Message } from "./email"
fn isAscii(s: string): boolean {
for i of 0..s.length {
let c = s.codeUnitAt(i) ?? 0
if c >= 127 || c < 32 {
return false
}
}
return true
}
/// `text` for a header: as it is when it is plain ASCII, otherwise as RFC 2047 encoded words of at most 75 characters,
/// never splitting a character.
export fn encodeHeader(text: string): string {
if isAscii(text) {
return text
}
let mut words: string[] = []
let mut chunk: int[] = []
for ch of text {
let bytes = Bytes.fromUtf8(ch).toList()
// 45 bytes of base64 fill an encoded word's 60 characters.
if chunk.length + bytes.length > 45 {
words.push(`=?UTF-8?B?${Bytes.of(chunk).toBase64()}?=`)
chunk = []
}
chunk.push(...bytes)
}
if chunk.length > 0 {
words.push(`=?UTF-8?B?${Bytes.of(chunk).toBase64()}?=`)
}
return words.join("\r\n ")
}
fn quoted(name: string): string {
return `"${name.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`
}
/// An address as a header writes it.
export fn formatAddress(address: Address): string {
let email = emailOf(address)
let name = nameOf(address)
if name == null || name == "" {
return email
}
return isAscii(name) ? `${quoted(name)} <${email}>` : `${encodeHeader(name)} <${email}>`
}
fn addressList(list: Address[]): string {
return list.map(formatAddress).join(",\r\n ")
}
/// One character of a line in quoted-printable. Spaces and tabs at the end of a line are encoded, as RFC 2045 requires.
fn encodeChar(ch: string, last: boolean): string {
let c = ch.codePointAt(0) ?? 0
if (c >= 33 && c <= 126 && c != 61) || ((c == 32 || c == 9) && !last) {
return ch
}
return Bytes.fromUtf8(ch)
.toList()
.map(b => "=" + str(b, { radix: 16 }).toUpperCase().padStart(2, "0"))
.join("")
}
/// `text` in quoted-printable (RFC 2045): lines of at most 76 characters, with no character split across two of them.
export fn quotedPrintable(text: string): string {
let source = text.replaceAll("\r\n", "\n").replaceAll("\r", "\n")
let mut lines: string[] = []
for line of source.split("\n") {
let mut all: string[] = []
for ch of line {
all.push(ch)
}
let mut out: string[] = []
let mut width = 0
for [i, ch] of all.entries() {
let piece = encodeChar(ch, i == all.length - 1)
if width + piece.length > 75 {
out.push("=\r\n")
width = 0
}
out.push(piece)
width += piece.length
}
lines.push(out.join(""))
}
return lines.join("\r\n")
}
fn wrapBase64(bytes: Bytes): string {
let text = bytes.toBase64()
let mut lines: string[] = []
let mut i = 0
while i < text.length {
lines.push(text.slice(i, i + 76))
i += 76
}
return lines.join("\r\n")
}
fn textPart(media: string, body: string): string {
return `Content-Type: ${media}; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n${quotedPrintable(body)}`
}
fn quotedParam(value: string): string {
return quoted(value)
}
fn percentEncoded(text: string): string {
let mut out: string[] = []
for b of Bytes.fromUtf8(text).toList() {
let plain = (b >= 48 && b <= 57) ||
(b >= 65 && b <= 90) ||
(b >= 97 && b <= 122) ||
b == 45 ||
b == 46 ||
b == 95
out.push(plain ? String.fromCharCode(b) : "%" + str(b, { radix: 16 }).toUpperCase().padStart(2, "0"))
}
return out.join("")
}
fn fileParam(name: string, filename: string): string {
return isAscii(filename)
? `${name}=${quotedParam(filename)}`
: `${name}*=UTF-8''${percentEncoded(filename)}`
}
fn attachmentPart(a: Attachment): string {
let media = a.type ?? "application/octet-stream"
let inline = a.contentId != null
let head = [
`Content-Type: ${media}; ${fileParam("name", a.filename)}`,
"Content-Transfer-Encoding: base64",
`Content-Disposition: ${inline ? "inline" : "attachment"}; ${fileParam("filename", a.filename)}`,
]
let cid = a.contentId
let lines = cid != null ? [...head, `Content-ID: <${cid}>`] : head
return `${lines.join("\r\n")}\r\n\r\n${wrapBase64(a.content)}`
}
fn multipart(subtype: string, boundary: string, parts: string[]): string {
let body = parts.map(p => `--${boundary}\r\n${p}\r\n`).join("")
return `Content-Type: multipart/${subtype};\r\n boundary="${boundary}"\r\n\r\n${body}--${boundary}--`
}
/// `id` makes the boundaries and the `Message-ID` repeatable, and `date` is the `Date` header (RFC 5322 form), for tests.
export type MimeOptions = { id?: string, date?: string }
fn domainOf(address: Address): string {
let email = emailOf(address)
return email.slice(email.indexOf("@") + 1)
}
/// The whole message as MIME text, with CRLF line endings and only ASCII in it: what an SMTP server is given after `DATA`.
/// `bcc` isn't written, since every recipient would see it.
///
/// ```weft
/// let source = toMime({ from: "a@example.com", to: ["b@example.com"], subject: "Hi", text: "Hello" })
/// ```
export fn toMime(message: Message, options: MimeOptions = {}): string {
let id = options.id ?? uuid()
let mut headers: string[] = [
`From: ${formatAddress(message.from)}`,
`To: ${addressList(message.to)}`,
]
let cc = message.cc ?? []
if cc.length > 0 {
headers.push(`Cc: ${addressList(cc)}`)
}
let replyTo = message.replyTo
if replyTo != null {
headers.push(`Reply-To: ${formatAddress(replyTo)}`)
}
headers.push(`Subject: ${encodeHeader(message.subject)}`)
let date = options.date
if date != null {
headers.push(`Date: ${date}`)
}
headers.push(`Message-ID: <${id}@${domainOf(message.from)}>`)
headers.push("MIME-Version: 1.0")
for [name, value] of message.headers ?? [] {
headers.push(`${name}: ${encodeHeader(value)}`)
}
let text = message.text ?? ""
let html = message.html ?? ""
let mut body = text != "" && html != ""
? multipart(
"alternative",
`alt-${id}`,
[textPart("text/plain", text), textPart("text/html", html)],
)
: html != "" ? textPart("text/html", html) : textPart("text/plain", text)
let attachments = message.attachments ?? []
let inline = attachments.filter(a => a.contentId != null)
let files = attachments.filter(a => a.contentId == null)
if inline.length > 0 {
body = multipart("related", `rel-${id}`, [body, ...inline.map(attachmentPart)])
}
if files.length > 0 {
body = multipart("mixed", `mix-${id}`, [body, ...files.map(attachmentPart)])
}
return `${headers.join("\r\n")}\r\n${body}\r\n`
}