Files
2026-11-27 10:08:51 +00:00

192 lines
6.8 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { SESv2Client, SendEmailCommand } from "@aws-sdk/client-sesv2";
import MailComposer from "nodemailer/lib/mail-composer";
import { addressesOf, formatMailbox } from "./address";
import { config, type TransportName } from "./config";
import type { StoredPayload } from "./queue";
export type SendResult = { providerMessageId: string };
export type SendFailure = Error & { retryable?: boolean; statusCode?: number };
function mimeOptions(payload: StoredPayload) {
return {
from: formatMailbox(payload.from),
to: payload.to.map(formatMailbox),
cc: payload.cc.map(formatMailbox),
bcc: payload.bcc.map(formatMailbox),
replyTo: payload.reply_to.map(formatMailbox),
subject: payload.subject,
text: payload.text,
html: payload.html,
headers: payload.headers,
attachments: payload.attachments.map((item) => ({
filename: item.filename,
content: Buffer.from(item.content, "base64"),
contentType: item.content_type,
cid: item.content_id,
})),
};
}
function buildRaw(payload: StoredPayload): Promise<Buffer> {
return new Promise((resolve, reject) => {
new MailComposer(mimeOptions(payload))
.compile()
.build((error, message) => {
if (error) reject(error);
else resolve(message);
});
});
}
function failure(message: string, statusCode?: number, retryable = false): SendFailure {
return Object.assign(new Error(message), { statusCode, retryable });
}
async function sendResend(payload: StoredPayload): Promise<SendResult> {
if (!config.resendApiKey) throw failure("RESEND_API_KEY fehlt");
const response = await fetch("https://api.resend.com/emails", {
method: "POST",
headers: {
authorization: `Bearer ${config.resendApiKey}`,
"content-type": "application/json",
},
body: JSON.stringify({
from: formatMailbox(payload.from),
to: payload.to.map(formatMailbox),
cc: payload.cc.map(formatMailbox),
bcc: payload.bcc.map(formatMailbox),
reply_to: payload.reply_to.map(formatMailbox),
subject: payload.subject,
html: payload.html,
text: payload.text,
headers: payload.headers,
attachments: payload.attachments.map((item) => ({
filename: item.filename,
content: item.content,
content_type: item.content_type,
content_id: item.content_id,
})),
tags: payload.tags,
}),
});
if (!response.ok) {
const detail = await response.text();
throw failure(`Resend ${response.status}: ${detail}`, response.status, response.status === 429 || response.status >= 500);
}
const data = (await response.json()) as { id?: string };
if (!data.id) throw failure("Resend lieferte keine Message-ID");
return { providerMessageId: data.id };
}
function scalewayMailbox(mailbox: { address: string; name?: string }) {
return mailbox.name ? { email: mailbox.address, name: mailbox.name } : { email: mailbox.address };
}
async function sendScaleway(payload: StoredPayload): Promise<SendResult> {
if (!config.scalewaySecretKey) throw failure("SCW_SECRET_KEY fehlt");
if (!config.scalewayProjectId) throw failure("SCW_PROJECT_ID fehlt");
const additionalHeaders = Object.entries(payload.headers).map(([key, value]) => ({ key, value }));
if (payload.reply_to.length) {
additionalHeaders.push({ key: "Reply-To", value: payload.reply_to.map(formatMailbox).join(", ") });
}
const endpoint = `https://api.scaleway.com/transactional-email/v1alpha1/regions/${encodeURIComponent(config.scalewayRegion)}/emails`;
let response: Response;
try {
response = await fetch(endpoint, {
method: "POST",
headers: {
"X-Auth-Token": config.scalewaySecretKey,
"content-type": "application/json",
},
body: JSON.stringify({
project_id: config.scalewayProjectId,
from: scalewayMailbox(payload.from),
to: payload.to.map(scalewayMailbox),
cc: payload.cc.map(scalewayMailbox),
bcc: payload.bcc.map(scalewayMailbox),
subject: payload.subject,
text: payload.text,
html: payload.html,
attachments: payload.attachments.map((item) => ({
name: item.filename,
type: item.content_type || "application/octet-stream",
content: item.content,
})),
additional_headers: additionalHeaders,
}),
});
} catch (error) {
throw Object.assign(error as Error, { retryable: true });
}
if (!response.ok) {
const detail = await response.text();
throw failure(
`Scaleway ${response.status}: ${detail}`,
response.status,
response.status === 429 || response.status >= 500,
);
}
const data = (await response.json()) as {
emails?: { id?: string; message_id?: string }[];
};
const first = data.emails?.[0];
const id = first?.message_id || first?.id;
if (!id) throw failure("Scaleway lieferte keine Message-ID");
return { providerMessageId: id };
}
async function sendSes(payload: StoredPayload): Promise<SendResult> {
const raw = await buildRaw(payload);
const client = new SESv2Client({ region: config.awsRegion });
try {
const result = await client.send(
new SendEmailCommand({
FromEmailAddress: formatMailbox(payload.from),
Destination: {
ToAddresses: addressesOf(payload.to),
CcAddresses: addressesOf(payload.cc),
BccAddresses: addressesOf(payload.bcc),
},
ReplyToAddresses: addressesOf(payload.reply_to),
Content: { Raw: { Data: raw } },
ConfigurationSetName: config.sesConfigurationSet,
EmailTags: payload.tags.map((tag) => ({ Name: tag.name, Value: tag.value })),
}),
);
if (!result.MessageId) throw failure("SES lieferte keine Message-ID");
return { providerMessageId: result.MessageId };
} catch (error) {
const status = (error as { $metadata?: { httpStatusCode?: number } }).$metadata?.httpStatusCode;
const name = (error as Error).name || "";
const retryable =
status === 429 ||
(status !== undefined && status >= 500) ||
/throttl|timeout|temporar|slow down|service unavailable/i.test(name) ||
/throttl|timeout|temporar|slow down|service unavailable/i.test((error as Error).message || "");
throw Object.assign(error as Error, { retryable, statusCode: status });
}
}
export async function sendStored(
payload: StoredPayload,
provider: TransportName = config.transport,
): Promise<SendResult> {
if (provider === "dry-run") {
console.log("[courier] dry-run", JSON.stringify({ from: payload.from, to: payload.to, subject: payload.subject }));
return { providerMessageId: `dry-${randomUUID()}` };
}
if (provider === "resend") return sendResend(payload);
if (provider === "scaleway") return sendScaleway(payload);
return sendSes(payload);
}