File size: 2,285 Bytes
062a991
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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" };
}