// `@weft/email`: messages, their validation and sending them through a transport. /// An email address, with or without a display name: `"ana@example.com"` or `{ email: "ana@example.com", name: "Ana" }`. export type Address = string | { email: string, name?: string } /// A file sent with a message. `type` is its media type (`application/octet-stream` unless given). `contentId` makes it an /// inline image, which the HTML shows with ``. export type Attachment = { filename: string, content: Bytes, type?: string, contentId?: string } /// A message. It needs a `from`, at least one recipient, a `subject` and an `html` or `text` body; send both when you can, /// since spam filters and some readers want the text. `headers` are extra headers, such as `List-Unsubscribe`. export type Message = { from: Address, to: Address[], cc?: Address[], bcc?: Address[], replyTo?: Address, subject: string, html?: string, text?: string, headers?: [string, string][], attachments?: Attachment[], } /// What sending gave: the provider's id for the message. `skipped` is true when `allowlist` kept it from being sent. export type Sent = { id: string, provider: string, skipped: boolean } /// Why a message wasn't sent. /// /// - `InvalidMessage`: the message can't be sent as it is, and nothing was attempted. `field` says what is wrong. /// - `Rejected`: the provider refused it (a bad key, an unverified domain, a suppressed recipient). Sending it again won't help. /// - `RateLimited`: too many messages. Try again later. /// - `ProviderFailure`: the provider had a problem. Try again later. /// - `ConnectionFailed`: the provider wasn't reached, or its answer broke off, so the message **may** have been sent. /// - `BadResponse`: the provider's answer couldn't be read, so the message may have been sent. export type EmailError = | InvalidMessage { field: string, message: string } | Rejected { status: float, code: string?, message: string } | RateLimited { message: string, retryAfter: float? } | ProviderFailure { status: float, message: string } | ConnectionFailed { message: string } | BadResponse { message: string } /// How messages leave: `resend(…)`, `postmark(…)`, `memory()`, or your own. export type Transport = { name: string, send: (message: Message) => Task } /// The plain address of an `Address`. export fn emailOf(address: Address): string { return address is string ? address : address.email } /// The display name of an `Address`, if it has one. export fn nameOf(address: Address): string? { return address is string ? null : address.name } fn hasLineBreak(s: string): boolean { return s.includes("\r") || s.includes("\n") } fn isAddressChar(c: int): boolean { // Printable ASCII but what would end an address in a header, or anything from outside ASCII (internationalised mail). return c > 32 && c != 127 && c != 60 && c != 62 && c != 40 && c != 41 && c != 44 && c != 59 && c != 58 && c != 34 && c != 92 && c != 91 && c != 93 } /// Whether `email` has the shape of an address: one `@`, something on both sides, nothing that would end it in a header. export fn isValidEmail(email: string): boolean { let at = email.indexOf("@") if at <= 0 || at != email.lastIndexOf("@") || at == email.length - 1 || email.length > 254 { return false } for i of 0..email.length { let c = email.codeUnitAt(i) ?? 0 if c != 64 && !isAddressChar(c) { return false } } let domain = email.slice(at + 1) return !domain.startsWith(".") && !domain.endsWith(".") && !domain.includes("..") } fn checkAddress(field: string, address: Address): void ! EmailError { let email = emailOf(address) if !isValidEmail(email) { fail InvalidMessage { field, message: `\`${email}\` isn't an email address` } } if hasLineBreak(nameOf(address) ?? "") { fail InvalidMessage { field, message: "a display name can't hold a line break" } } } fn isHeaderName(name: string): boolean { if name == "" { return false } for i of 0..name.length { let c = name.codeUnitAt(i) ?? 0 if c <= 32 || c >= 127 || c == 58 { return false } } return true } /// Checks a message before it is sent. Line breaks in a subject, a name or a header are refused, because they would let /// whoever supplied that text add headers of their own. export fn validate(message: Message): void ! EmailError { try checkAddress("from", message.from) let to = message.to let cc = message.cc ?? [] let bcc = message.bcc ?? [] if to.length + cc.length + bcc.length == 0 { fail InvalidMessage { field: "to", message: "a message needs at least one recipient" } } for address of to { try checkAddress("to", address) } for address of cc { try checkAddress("cc", address) } for address of bcc { try checkAddress("bcc", address) } let replyTo = message.replyTo if replyTo != null { try checkAddress("replyTo", replyTo) } if message.subject.trim() == "" { fail InvalidMessage { field: "subject", message: "a message needs a subject" } } if hasLineBreak(message.subject) { fail InvalidMessage { field: "subject", message: "a subject can't hold a line break" } } if (message.html ?? "") == "" && (message.text ?? "") == "" { fail InvalidMessage { field: "html", message: "a message needs an html or a text body" } } for [name, value] of message.headers ?? [] { if !isHeaderName(name) { fail InvalidMessage { field: "headers", message: `\`${name}\` isn't a header name` } } if hasLineBreak(value) { fail InvalidMessage { field: "headers", message: `the header \`${name}\` can't hold a line break`, } } } for attachment of message.attachments ?? [] { if attachment.filename == "" || hasLineBreak(attachment.filename) { fail InvalidMessage { field: "attachments", message: "an attachment needs a file name on one line", } } } } /// Checks a message and sends it. /// /// ```weft /// import { send } from "@weft/email" /// import { resend } from "@weft/email/resend" /// /// let mail = resend({ apiKey: env("RESEND_API_KEY")! }) /// let sent = try await send(mail, { /// from: { email: "info@example.com", name: "Example" }, /// to: ["ana@example.com"], /// subject: "Your ticket", /// html: "

See you there.

", /// text: "See you there.", /// }) /// ``` export async fn send(transport: Transport, message: Message): Sent ! EmailError { try validate(message) return try await transport.send(message) } /// `inner`, sending only to the addresses listed (`"*"` lifts the limit). Other messages are skipped, not failed: staging /// sites use this so that real customers never get a test email. export fn allowlist(inner: Transport, allowed: string[]): Transport { let list = allowed.map(a => a.trim().toLowerCase()) let open = list.includes("*") return { name: inner.name, send: async message => { let all = [...message.to, ...(message.cc ?? []), ...(message.bcc ?? [])] if !open && !all.every(a => list.includes(emailOf(a).trim().toLowerCase())) { return { id: "", provider: inner.name, skipped: true } } return try await inner.send(message) }, } } let mut sentMessages: Message[] = [] /// A transport that keeps messages in this process instead of sending them, for tests. Read them with `outbox()`. export fn memory(): Transport { return { name: "memory", send: async message => { sentMessages.push(message) return { id: `memory-${sentMessages.length}`, provider: "memory", skipped: false } }, } } /// What `memory()` has been given, oldest first. export fn outbox(): Message[] { return sentMessages } /// Empties `outbox()`. export fn clearOutbox() { sentMessages = [] }