2,114 bytes · the TypeScript implementation · view raw
import { chooseProvider, io } from"./funeio.ts";
importtype { EmailMessage, SentEmail } from"./email_send_types.ts";
import { sendWithResend } from"./email_send_adapter_resend.ts";
import { sendWithSmtp } from"./email_send_adapter_smtp.ts";
import { sendWithLog } from"./email_send_adapter_log.ts";
const PROVIDERS = ["resend", "smtp", "log"];
// name@example.com, or Name <name@example.com>: one @, no spaces in the address.const ADDRESS = /^(?:[^<>@]*<\s*[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+\s*>|[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+)$/;
function checkAddress(value: string, what: string): void {
if (typeof value !== "string" || !ADDRESS.test(value.trim())) {
thrownew Error(`${what} ${JSON.stringify(value)} is not an email address`);
}
}
/** * Send one email through the provider EMAIL_PROVIDER names. The message is * checked before anything is sent, so a bad address or a missing body never * reaches the provider; what the provider refuses is thrown with its reason. */exportasyncfunction sendEmail(message: EmailMessage): Promise<SentEmail> {
if (!message || !Array.isArray(message.to) || message.to.length === 0) {
thrownew Error("an email needs at least one recipient in to");
}
for (const to of message.to) checkAddress(to, "to");
for (const cc of message.cc ?? []) checkAddress(cc, "cc");
for (const bcc of message.bcc ?? []) checkAddress(bcc, "bcc");
if (typeof message.subject !== "string" || /[\r\n]/.test(message.subject)) {
thrownew Error("the subject is one line of text");
}
if (!message.text && !message.html) thrownew Error("an email needs a text or an html body");
constfrom = message.from ?? io().env("EMAIL_FROM");
if (!from) thrownew Error("no From address: give message.from, or set EMAIL_FROM");
checkAddress(from, "from");
if (message.replyTo !== undefined) checkAddress(message.replyTo, "replyTo");
const provider = chooseProvider("EMAIL_PROVIDER", PROVIDERS);
if (provider === "resend") return sendWithResend(message, from);
if (provider === "smtp") return sendWithSmtp(message, from);
return sendWithLog(message, from);
}