AgPerry's picture
Add files using upload-large-folder tool
062a991 verified
Raw History Blame Contribute Delete
2.29 kB
import nodemailer from "nodemailer";
import { ApiError } from "./api";
type TransactionalEmail = {
to: string;
subject: string;
text: string;
html: string;
previewUrl?: string;
};
function deliveryMode() {
const configured = process.env.EMAIL_DELIVERY_MODE?.trim().toLowerCase();
if (configured === "smtp" || configured === "console") return configured;
return process.env.SMTP_HOST ? "smtp" : "console";
}
export async function sendTransactionalEmail(
message: TransactionalEmail,
): Promise<{ delivery: string; previewUrl?: string }> {
const apiUrl = process.env.WEBSITEBENCH_MAIL_API_URL?.trim();
const apiToken = process.env.WEBSITEBENCH_MAIL_API_TOKEN?.trim();
const apiFrom = process.env.WEBSITEBENCH_MAIL_FROM?.trim();
if (apiUrl && apiToken && apiFrom) {
const response = await fetch(apiUrl, {
method: "POST",
headers: {
authorization: `Bearer ${apiToken}`,
"content-type": "application/json",
accept: "application/json",
},
body: JSON.stringify({ from: apiFrom, to: [message.to], subject: message.subject, text: message.text }),
}).catch(() => null);
const result = await response?.json().catch(() => null) as { id?: string } | null;
if (!response?.ok || !result?.id) {
throw new ApiError(503, "Email delivery failed.", "email_delivery_failed");
}
return { delivery: "mailpit" };
}
if (deliveryMode() === "console") {
throw new ApiError(503, "SMTP email delivery is required.", "email_not_configured");
}
const host = process.env.SMTP_HOST;
const from = process.env.MAIL_FROM ?? process.env.SMTP_FROM;
if (!host || !from) {
throw new ApiError(503, "SMTP_HOST and MAIL_FROM must be configured for email delivery.", "email_not_configured");
}
const port = Number(process.env.SMTP_PORT ?? 587);
const transporter = nodemailer.createTransport({
host,
port,
secure: process.env.SMTP_SECURE === "true" || port === 465,
auth: process.env.SMTP_USER ? {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS ?? "",
} : undefined,
});
await transporter.sendMail({
from,
to: message.to,
subject: message.subject,
text: message.text,
html: message.html,
});
return { delivery: "smtp" };
}