Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { io, requireEnv } from "./funeio.ts";
import type { Connection } from "./funeio.ts";
import type { EmailMessage, SentEmail } from "./email_send_types.ts";
import { base64Encode } from "./encoding_base64.ts"; ← from encoding.base64 ^1.0.0 · built alongside by fune
import { hexEncode } from "./encoding_hex.ts"; ← from encoding.hex ^1.0.0 · built alongside by fune
import { utf8Encode } from "./encoding_utf8.ts"; ← from encoding.utf8 ^1.0.0 · built alongside by fune
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
// The address inside "Name <name@example.com>", or the address itself.
function bareAddress(address: string): string {
const m = /<\s*([^<>\s]+)\s*>/.exec(address);
return (m ? m[1] : address).trim();
}
// An RFC 5322 date, in UTC.
function mailDate(ms: number): string {
const d = new Date(ms);
const two = (n: number) => String(n).padStart(2, "0");
return `${DAYS[d.getUTCDay()]}, ${two(d.getUTCDate())} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()} ${two(d.getUTCHours())}:${two(d.getUTCMinutes())}:${two(d.getUTCSeconds())} +0000`;
}
// A header value as is when it is printable ASCII, else an RFC 2047 encoded word.
function headerText(text: string): string {
return /^[\x20-\x7e]*$/.test(text) ? text : `=?UTF-8?B?${base64Encode(utf8Encode(text))}?=`;
}
// A body as base64 in lines of 76, which no line of can start with a dot.
function base64Lines(text: string): string[] {
const all = base64Encode(utf8Encode(text));
const out: string[] = [];
for (let i = 0; i < all.length; i += 76) out.push(all.slice(i, i + 76));
return out;
}
/** The message as the DATA command sends it, line by line (RFC 5322, MIME). */
function messageLines(message: EmailMessage, from: string, messageId: string, boundary: string): string[] {
const head = [`From: ${headerText(from)}`, `To: ${message.to.join(", ")}`];
if (message.cc?.length) head.push(`Cc: ${message.cc.join(", ")}`);
if (message.replyTo) head.push(`Reply-To: ${message.replyTo}`);
head.push(`Subject: ${headerText(message.subject)}`, `Date: ${mailDate(io().now())}`, `Message-ID: ${messageId}`, "MIME-Version: 1.0");
const part = (type: string, text: string) => [`Content-Type: text/${type}; charset=utf-8`, "Content-Transfer-Encoding: base64", "", ...base64Lines(text)];
if (message.text && message.html) {
return [
...head,
`Content-Type: multipart/alternative; boundary="${boundary}"`,
"",
`--${boundary}`,
...part("plain", message.text),
`--${boundary}`,
...part("html", message.html),
`--${boundary}--`,
];
}
return [...head, ...(message.text ? part("plain", message.text) : part("html", message.html ?? ""))];
}
// One reply, however many lines it runs to (250-... then 250 ...).
async function reply(conn: Connection): Promise<{ code: number; lines: string[] }> {
const lines: string[] = [];
for (;;) {
const line = await conn.receive();
lines.push(line);
if (!/^\d{3}-/.test(line)) break;
}
return { code: Number(lines[lines.length - 1].slice(0, 3)), lines };
}
async function expectReply(conn: Connection, want: number[], step: string): Promise<{ code: number; lines: string[] }> {
const r = await reply(conn);
if (!want.includes(r.code)) throw new Error(`smtp: ${step} was answered ${r.lines.join(" / ")}`);
return r;
}
async function command(conn: Connection, line: string, want: number[], step: string): Promise<{ code: number; lines: string[] }> {
await conn.send(`${line}\r\n`);
return expectReply(conn, want, step);
}
/**
* SMTP: the server SMTP_URL names, over implicit TLS (smtps:, port 465) or
* upgraded with STARTTLS (smtp:, port 587), which it refuses to skip: a
* password never crosses the network in the clear.
*/
export async function sendWithSmtp(message: EmailMessage, from: string): Promise<SentEmail> {
const raw = requireEnv("SMTP_URL");
// smtps://user:password@host:465 or smtp://user:password@host:587
const m = /^(smtps?):\/\/(?:([^:@/]*)(?::([^@/]*))?@)?([^:@/?#]+)(?::(\d+))?\/?$/.exec(raw.trim());
if (!m) throw new Error("SMTP_URL is not smtps://user:password@host:465 or smtp://user:password@host:587");
const tls = m[1] === "smtps";
const host = m[4];
const port = m[5] ? Number(m[5]) : tls ? 465 : 587;
const user = decodeURIComponent(m[2] ?? "");
const password = decodeURIComponent(m[3] ?? "");
const sender = bareAddress(from);
const domain = sender.slice(sender.indexOf("@") + 1);
const random = io().randomBytes(16);
const messageId = `<${hexEncode(random)}@${domain}>`;
const boundary = `fune-${hexEncode(random.slice(0, 8))}`;
const data = messageLines(message, from, messageId, boundary);
const conn = await io().connect(host, port, tls);
try {
await expectReply(conn, [220], "the greeting");
let hello = await command(conn, `EHLO ${domain}`, [250], "EHLO");
if (!tls) {
if (!hello.lines.some((l) => /^250[ -]STARTTLS\b/i.test(l))) {
throw new Error(`smtp: ${host}:${port} does not offer STARTTLS, and the password is never sent in the clear; use smtps:// if it takes TLS on another port`);
}
await command(conn, "STARTTLS", [220], "STARTTLS");
await conn.startTls(host);
hello = await command(conn, `EHLO ${domain}`, [250], "EHLO");
}
if (user) await command(conn, `AUTH PLAIN ${base64Encode(utf8Encode(`\u0000${user}\u0000${password}`))}`, [235], "AUTH PLAIN");
await command(conn, `MAIL FROM:<${sender}>`, [250], "MAIL FROM");
for (const to of [...message.to, ...(message.cc ?? []), ...(message.bcc ?? [])]) {
await command(conn, `RCPT TO:<${bareAddress(to)}>`, [250, 251], `RCPT TO ${bareAddress(to)}`);
}
await command(conn, "DATA", [354], "DATA");
const done = await command(conn, `${data.join("\r\n")}\r\n.`, [250], "the message");
await command(conn, "QUIT", [221], "QUIT");
const queued = /queued as\s+([^\s]+)/i.exec(done.lines.join(" "));
return { provider: "smtp", id: queued ? queued[1] : messageId };
} finally {
await conn.close();
}
}