import { Buffer } from "node:buffer"; import { randomBytes } from "node:crypto"; import { readFileSync, statSync } from "node:fs"; import { createConnection, type Socket } from "node:net"; import { basename, extname } from "node:path"; import { connect as tlsConnect, type TLSSocket } from "node:tls"; import { defineTool, FilePath, Type } from "@toolpal/tool"; const MAX_TOTAL_ATTACHMENT_BYTES = 10 * 1024 * 1024; const EMAIL_RE = /^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/; const MIME_BY_EXT: Record = { ".pdf": "application/pdf", ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".csv": "text/csv; charset=utf-8", ".txt": "text/plain; charset=utf-8", ".md": "text/markdown; charset=utf-8", ".json": "application/json", ".ics": "text/calendar; charset=utf-8", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".svg": "image/svg+xml", ".zip": "application/zip", }; interface Attachment { filename: string; contentType: string; data: Buffer; } function assertCleanHeader(label: string, value: string): string { if (/[\r\n]/.test(value)) { throw new Error(`${label} cannot contain line breaks.`); } return value.trim(); } function extractAddress(raw: string): string { const cleaned = assertCleanHeader("Address", raw); const angle = cleaned.match(/<([^<>]+)>/); const addr = (angle ? angle[1] : cleaned).trim(); if (!EMAIL_RE.test(addr)) throw new Error(`Invalid email address "${raw}".`); return addr; } function encodeHeaderValue(value: string): string { const clean = assertCleanHeader("Header", value); if (/^[\x20-\x7e]*$/.test(clean)) return clean; return `=?UTF-8?B?${Buffer.from(clean, "utf8").toString("base64")}?=`; } function wrapBase64(b64: string): string { const lines: string[] = []; for (let i = 0; i < b64.length; i += 76) lines.push(b64.slice(i, i + 76)); return lines.join("\r\n"); } function loadAttachments(paths: string[] | undefined): Attachment[] { if (!paths?.length) return []; let total = 0; for (const p of paths) { total += statSync(p).size; if (total > MAX_TOTAL_ATTACHMENT_BYTES) { throw new Error("Total attachment size exceeds the 10 MB limit."); } } return paths.map((p) => { const filename = assertCleanHeader("Attachment filename", basename(p)); const ext = extname(filename).toLowerCase(); return { filename, contentType: MIME_BY_EXT[ext] ?? "application/octet-stream", data: readFileSync(p), }; }); } function buildMimeMessage(opts: { from: string; to: string[]; cc: string[]; replyTo?: string; subject: string; text?: string; html?: string; attachments: Attachment[]; messageId: string; }): string { const headers = [ `From: ${assertCleanHeader("from", opts.from)}`, `To: ${opts.to.map((a) => assertCleanHeader("to", a)).join(", ")}`, ...(opts.cc.length ? [`Cc: ${opts.cc.map((a) => assertCleanHeader("cc", a)).join(", ")}`] : []), ...(opts.replyTo ? [`Reply-To: ${assertCleanHeader("replyTo", opts.replyTo)}`] : []), `Subject: ${encodeHeaderValue(opts.subject)}`, `Date: ${new Date().toUTCString()}`, `Message-ID: <${opts.messageId}>`, "MIME-Version: 1.0", ]; const textPart = opts.text !== undefined ? [ "Content-Type: text/plain; charset=utf-8", "Content-Transfer-Encoding: base64", "", wrapBase64(Buffer.from(opts.text, "utf8").toString("base64")), ].join("\r\n") : undefined; const htmlPart = opts.html !== undefined ? [ "Content-Type: text/html; charset=utf-8", "Content-Transfer-Encoding: base64", "", wrapBase64(Buffer.from(opts.html, "utf8").toString("base64")), ].join("\r\n") : undefined; let bodySection: string; let bodyContentType: string; if (textPart && htmlPart) { const altBoundary = `alt_${randomBytes(12).toString("hex")}`; bodyContentType = `multipart/alternative; boundary="${altBoundary}"`; bodySection = [ `--${altBoundary}`, textPart, `--${altBoundary}`, htmlPart, `--${altBoundary}--`, ].join("\r\n"); } else if (htmlPart) { bodyContentType = "text/html; charset=utf-8"; bodySection = [ "Content-Transfer-Encoding: base64", "", wrapBase64(Buffer.from(opts.html as string, "utf8").toString("base64")), ].join("\r\n"); } else { bodyContentType = "text/plain; charset=utf-8"; bodySection = [ "Content-Transfer-Encoding: base64", "", wrapBase64(Buffer.from(opts.text ?? "", "utf8").toString("base64")), ].join("\r\n"); } if (opts.attachments.length === 0) { if (textPart && htmlPart) { return `${headers.join("\r\n")}\r\nContent-Type: ${bodyContentType}\r\n\r\n${bodySection}\r\n`; } return `${headers.join("\r\n")}\r\nContent-Type: ${bodyContentType}\r\n${bodySection}\r\n`; } const mixBoundary = `mix_${randomBytes(12).toString("hex")}`; const parts: string[] = []; if (textPart && htmlPart) { parts.push(`--${mixBoundary}\r\nContent-Type: ${bodyContentType}\r\n\r\n${bodySection}`); } else { parts.push(`--${mixBoundary}\r\nContent-Type: ${bodyContentType}\r\n${bodySection}`); } for (const att of opts.attachments) { const safeName = att.filename.replace(/["\\]/g, "_"); parts.push( [ `--${mixBoundary}`, `Content-Type: ${att.contentType}; name="${safeName}"`, `Content-Disposition: attachment; filename="${safeName}"`, "Content-Transfer-Encoding: base64", "", wrapBase64(att.data.toString("base64")), ].join("\r\n"), ); } parts.push(`--${mixBoundary}--`); return `${headers.join("\r\n")}\r\nContent-Type: multipart/mixed; boundary="${mixBoundary}"\r\n\r\n${parts.join("\r\n")}\r\n`; } async function sendViaResend(opts: { apiKey: string; from: string; to: string[]; cc: string[]; bcc: string[]; replyTo?: string; subject: string; text?: string; html?: string; attachments: Attachment[]; }): Promise { const payload: Record = { from: opts.from, to: opts.to, subject: opts.subject, ...(opts.cc.length ? { cc: opts.cc } : {}), ...(opts.bcc.length ? { bcc: opts.bcc } : {}), ...(opts.replyTo ? { reply_to: opts.replyTo } : {}), ...(opts.text !== undefined ? { text: opts.text } : {}), ...(opts.html !== undefined ? { html: opts.html } : {}), ...(opts.attachments.length ? { attachments: opts.attachments.map((a) => ({ filename: a.filename, content: a.data.toString("base64"), })), } : {}), }; const res = await fetch("https://api.resend.com/emails", { method: "POST", headers: { authorization: `Bearer ${opts.apiKey}`, "content-type": "application/json", }, body: JSON.stringify(payload), signal: AbortSignal.timeout(20_000), }); const body = (await res.json().catch(() => ({}))) as { id?: string; message?: string }; if (!res.ok) { throw new Error(`Resend returned HTTP ${res.status}: ${body.message ?? res.statusText}`); } return body.id ?? "sent"; } async function sendViaSmtp(opts: { smtpUrl: string; from: string; to: string[]; cc: string[]; bcc: string[]; replyTo?: string; subject: string; text?: string; html?: string; attachments: Attachment[]; }): Promise { const parsed = new URL(opts.smtpUrl); if (parsed.protocol !== "smtp:" && parsed.protocol !== "smtps:") { throw new Error("SMTP_URL must start with smtp:// or smtps://"); } const implicitTls = parsed.protocol === "smtps:"; const host = parsed.hostname; const port = parsed.port ? Number(parsed.port) : implicitTls ? 465 : 587; const user = parsed.username ? decodeURIComponent(parsed.username) : ""; const pass = parsed.password ? decodeURIComponent(parsed.password) : ""; const fromAddr = extractAddress(opts.from); const domain = fromAddr.split("@")[1] || "toolpal.local"; const messageId = `${Date.now()}.${randomBytes(8).toString("hex")}@${domain}`; const mime = buildMimeMessage({ ...opts, messageId }); const recipients = [...opts.to, ...opts.cc, ...opts.bcc].map(extractAddress); let sock: Socket | TLSSocket = await new Promise((resolve, reject) => { const s = implicitTls ? tlsConnect({ host, port, servername: host }) : createConnection({ host, port }); const timer = setTimeout(() => { s.destroy(); reject(new Error(`SMTP connection to ${host}:${port} timed out.`)); }, 15_000); s.once(implicitTls ? "secureConnect" : "connect", () => { clearTimeout(timer); resolve(s); }); s.once("error", (err) => { clearTimeout(timer); reject(err); }); }); let buffer = ""; let waiting: ((line: string) => void) | null = null; let waitReject: ((err: Error) => void) | null = null; const lines: string[] = []; const attachReaders = (s: Socket | TLSSocket) => { s.setEncoding("utf8"); s.setTimeout(20_000, () => { const err = new Error("SMTP socket timed out."); s.destroy(err); }); s.on("data", (chunk: string) => { buffer += chunk; let idx: number; while ((idx = buffer.indexOf("\r\n")) !== -1) { const line = buffer.slice(0, idx); buffer = buffer.slice(idx + 2); if (waiting) { const resolve = waiting; waiting = null; waitReject = null; resolve(line); } else { lines.push(line); } } }); s.on("error", (err) => { if (waitReject) { const rej = waitReject; waiting = null; waitReject = null; rej(err); } }); s.on("close", () => { if (waitReject) { const rej = waitReject; waiting = null; waitReject = null; rej(new Error("SMTP connection closed unexpectedly.")); } }); }; attachReaders(sock); const nextLine = (): Promise => { if (lines.length > 0) return Promise.resolve(lines.shift() as string); return new Promise((resolve, reject) => { waiting = resolve; waitReject = reject; }); }; const readReply = async (): Promise<{ code: number; text: string }> => { const collected: string[] = []; while (true) { const line = await nextLine(); collected.push(line); if (/^\d{3}(?: |$)/.test(line)) { return { code: Number(line.slice(0, 3)), text: collected.join("\n") }; } } }; const sendCmd = async (cmd: string, expected: number[]): Promise<{ code: number; text: string }> => { sock.write(`${cmd}\r\n`); const reply = await readReply(); if (!expected.includes(reply.code)) { throw new Error(`SMTP error (${reply.code}): ${reply.text.slice(0, 300)}`); } return reply; }; try { const greeting = await readReply(); if (greeting.code !== 220) throw new Error(`SMTP greeting failed (${greeting.code}).`); let ehlo = await sendCmd(`EHLO ${domain}`, [250]); if (!implicitTls && /\bSTARTTLS\b/i.test(ehlo.text)) { await sendCmd("STARTTLS", [220]); sock.removeAllListeners("data"); sock.removeAllListeners("error"); sock.removeAllListeners("close"); sock = await new Promise((resolve, reject) => { const upgraded = tlsConnect({ socket: sock, servername: host }); upgraded.once("secureConnect", () => resolve(upgraded)); upgraded.once("error", reject); }); attachReaders(sock); ehlo = await sendCmd(`EHLO ${domain}`, [250]); } if (user || pass) { if (/\bAUTH\b[^\n]*\bPLAIN\b/i.test(ehlo.text)) { const creds = Buffer.from(`\0${user}\0${pass}`, "utf8").toString("base64"); await sendCmd(`AUTH PLAIN ${creds}`, [235]); } else { await sendCmd("AUTH LOGIN", [334]); await sendCmd(Buffer.from(user, "utf8").toString("base64"), [334]); await sendCmd(Buffer.from(pass, "utf8").toString("base64"), [235]); } } await sendCmd(`MAIL FROM:<${fromAddr}>`, [250]); for (const rcpt of recipients) { await sendCmd(`RCPT TO:<${rcpt}>`, [250, 251]); } await sendCmd("DATA", [354]); // RFC 5321 dot-stuffing: any line starting with "." gets an extra leading "." const stuffed = mime.replace(/\r?\n/g, "\r\n").replace(/(^|\r\n)\./g, "$1.."); sock.write(`${stuffed}\r\n.\r\n`); const dataReply = await readReply(); if (dataReply.code !== 250) { throw new Error(`SMTP DATA rejected (${dataReply.code}): ${dataReply.text.slice(0, 300)}`); } await sendCmd("QUIT", [221]).catch(() => undefined); return messageId; } finally { sock.destroy(); } } export default defineTool({ description: "Sends a plain-text or HTML email with optional file attachments via Resend (RESEND_API_KEY) or SMTP (SMTP_URL, supporting smtps:// and STARTTLS). Set EMAIL_FROM or pass `from` per call. Completes automated workflows alongside @toolpal/notify.", input: Type.Object({ to: Type.Union([ Type.String({ minLength: 3, maxLength: 320 }), Type.Array(Type.String({ minLength: 3, maxLength: 320 }), { minItems: 1, maxItems: 50 }), ]), subject: Type.String({ minLength: 1, maxLength: 998 }), text: Type.Optional(Type.String({ maxLength: 500_000, description: "Plain-text email body" })), html: Type.Optional(Type.String({ maxLength: 500_000, description: "HTML email body" })), from: Type.Optional( Type.String({ maxLength: 320, description: 'Sender address, e.g. "Ops "; defaults to EMAIL_FROM', }), ), cc: Type.Optional(Type.Array(Type.String({ minLength: 3, maxLength: 320 }), { maxItems: 50 })), bcc: Type.Optional(Type.Array(Type.String({ minLength: 3, maxLength: 320 }), { maxItems: 50 })), replyTo: Type.Optional(Type.String({ minLength: 3, maxLength: 320 })), files: Type.Optional( Type.Array(FilePath({ description: "File attachments (10 MB total max)" }), { maxItems: 10 }), ), provider: Type.Optional( Type.Union([Type.Literal("auto"), Type.Literal("resend"), Type.Literal("smtp")], { description: "Delivery backend; auto (default) uses RESEND_API_KEY if set, else SMTP_URL", }), ), }), output: Type.Object({ provider: Type.Union([Type.Literal("resend"), Type.Literal("smtp")]), messageId: Type.String(), from: Type.String(), recipients: Type.Integer(), attachments: Type.Integer(), }), handler: async (input, ctx) => { if (input.text === undefined && input.html === undefined) { throw new Error("Provide text, html, or both."); } const from = input.from ?? process.env.EMAIL_FROM; if (!from) { throw new Error('Sender address is required: pass "from" or set EMAIL_FROM.'); } extractAddress(from); const to = (Array.isArray(input.to) ? input.to : [input.to]).map((a) => { extractAddress(a); return a.trim(); }); const cc = (input.cc ?? []).map((a) => { extractAddress(a); return a.trim(); }); const bcc = (input.bcc ?? []).map((a) => { extractAddress(a); return a.trim(); }); if (input.replyTo) extractAddress(input.replyTo); assertCleanHeader("subject", input.subject); const attachments = loadAttachments(input.files); const resendKey = process.env.RESEND_API_KEY; const smtpUrl = process.env.SMTP_URL; let provider: "resend" | "smtp"; if (input.provider === "resend") { if (!resendKey) throw new Error("RESEND_API_KEY is not set."); provider = "resend"; } else if (input.provider === "smtp") { if (!smtpUrl) throw new Error("SMTP_URL is not set."); provider = "smtp"; } else if (resendKey) { provider = "resend"; } else if (smtpUrl) { provider = "smtp"; } else { throw new Error("Configure either RESEND_API_KEY or SMTP_URL to send email."); } const messageId = provider === "resend" ? await sendViaResend({ apiKey: resendKey as string, from, to, cc, bcc, replyTo: input.replyTo, subject: input.subject, text: input.text, html: input.html, attachments, }) : await sendViaSmtp({ smtpUrl: smtpUrl as string, from, to, cc, bcc, replyTo: input.replyTo, subject: input.subject, text: input.text, html: input.html, attachments, }); const recipients = to.length + cc.length + bcc.length; ctx.log("info", `Sent email via ${provider} to ${recipients} recipient(s)`, { messageId }); return { provider, messageId, from, recipients, attachments: attachments.length, }; }, });