// Sending through Resend (https://resend.com/docs/api-reference/emails/send-email). import { fetch } from "std/http" import { emailOf } from "./email" import type { Address, EmailError, Message, Transport } from "./email" /// `baseUrl` is for tests. `idempotencyKey` is sent with every message when given as a function of the message, so that /// sending one again by accident does nothing. export type ResendOptions = { apiKey: string, baseUrl?: string, timeout?: float, idempotencyKey?: (message: Message) => string?, } fn text(value: json): string? { return value is string ? value : null } fn plain(address: Address): string { // Resend reads a UTF-8 display name directly, so it isn't encoded as a mail header would be. let email = emailOf(address) let name = address is string ? null : address.name if name == null || name == "" { return email } return `"${name.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}" <${email}>` } /// The JSON Resend is sent for a message. export fn payload(message: Message): json { let mut body: json = { from: plain(message.from), to: message.to.map(plain), subject: message.subject, } let cc = message.cc ?? [] if cc.length > 0 { body["cc"] = cc.map(plain) } let bcc = message.bcc ?? [] if bcc.length > 0 { body["bcc"] = bcc.map(plain) } let replyTo = message.replyTo if replyTo != null { body["reply_to"] = plain(replyTo) } let html = message.html if html != null && html != "" { body["html"] = html } let plainText = message.text if plainText != null && plainText != "" { body["text"] = plainText } let headers = message.headers ?? [] if headers.length > 0 { body["headers"] = Map(headers) } let attachments = message.attachments ?? [] if attachments.length > 0 { let files: json[] = attachments.map(a => { let mut file: json = { filename: a.filename, content: a.content.toBase64() } let media = a.type if media != null { file["content_type"] = media } let cid = a.contentId if cid != null { file["content_id"] = cid } return file }) body["attachments"] = files } return body } /// The error for an answer that isn't a success. export fn failureOf(status: float, body: json, retryAfter: string?): EmailError { let message = text(body.message) ?? `Resend answered ${status}` if status == 429 { return RateLimited { message, retryAfter: retryAfter != null ? secondsOf(retryAfter) : null } } if status >= 500 { return ProviderFailure { status, message } } return Rejected { status, code: text(body.name), message } } fn secondsOf(value: string): float? { let n = value.trim() let mut total = 0 if n == "" { return null } for ch of n { let c = ch.codeUnitAt(0) ?? 0 if c < 48 || c > 57 { return null } total = total * 10 + (c - 48) } return total } /// A transport that sends through Resend. It needs `http.fetch`. /// /// ```weft /// let mail = resend({ apiKey: env("RESEND_API_KEY")! }) /// ``` export fn resend(options: ResendOptions): Transport { let url = `${options.baseUrl ?? "https://api.resend.com"}/emails` let timeout = options.timeout ?? 30000 let keyOf = options.idempotencyKey let apiKey = options.apiKey return { name: "resend", send: async message => { let mut headers: [string, string][] = [ ["authorization", `Bearer ${apiKey}`], ["user-agent", "weft-email/0.1.0"], ] let key = keyOf != null ? keyOf(message) : null if key != null { headers.push(["idempotency-key", key]) } let res, err = try await fetch( url, { method: "POST", headers, json: payload(message), timeout }, ) if err != null { fail ConnectionFailed { message: `could not reach Resend: ${err.message}` } } let answer = try await res.json() else null if !res.ok { fail failureOf(res.status, answer, res.headers.get("retry-after")) } let id = text(answer.id) if id == null { fail BadResponse { message: "Resend's answer has no id" } } return { id, provider: "resend", skipped: false } }, } }