since3-portal/modules/shared/mail/send-mail.ts

88 lines
3.2 KiB
TypeScript

import "server-only"
import { readFileSync } from "node:fs"
import path from "node:path"
import { COMPANY } from "@/modules/shared/data/company"
import { LOGO_CIDS } from "./layout"
const RESEND_ENDPOINT = "https://api.resend.com/emails"
const DEFAULT_FROM = "Since3 <portal@contact.since3.de>"
const ASSET_DIR = path.join(process.cwd(), "modules/shared/mail/assets")
let logoAttachments: { filename: string; content: string; content_type: string; content_id: string }[] | null = null
function logos() {
logoAttachments ??= (["light", "dark"] as const).map((variant) => ({
filename: `since3-logo-${variant}.png`,
content: readFileSync(path.join(ASSET_DIR, `since3-logo-${variant}.png`)).toString("base64"),
content_type: "image/png",
content_id: LOGO_CIDS[variant],
}))
return logoAttachments
}
export type MailAttachment = { filename: string; content: Uint8Array; contentType: string }
export type SendMailResult = { ok: true; id: string } | { ok: false; error: string }
// Wirft nie: Mailversand ist Nebeneffekt, der eigentliche Vorgang (Client, Rechnung, ...) soll davon nicht scheitern.
export async function sendMail({
to,
subject,
html,
type,
attachments = [],
idempotencyKey,
}: {
to: string
subject: string
html: string
type: "welcome" | "credential" | "invoice"
attachments?: MailAttachment[]
idempotencyKey?: string
}): Promise<SendMailResult> {
const apiKey = process.env.RESEND_SECRET_API_KEY
if (!apiKey) {
console.error("[mail] RESEND_SECRET_API_KEY ist nicht gesetzt.")
return { ok: false, error: "Mailversand ist nicht eingerichtet." }
}
try {
const response = await fetch(RESEND_ENDPOINT, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
},
body: JSON.stringify({
from: process.env.MAIL_FROM ?? DEFAULT_FROM,
to: [to],
reply_to: COMPANY.email,
subject,
html,
tags: [{ name: "type", value: type }],
attachments: [
...logos(),
...attachments.map((attachment) => ({
filename: attachment.filename,
content: Buffer.from(attachment.content).toString("base64"),
content_type: attachment.contentType,
})),
],
}),
signal: AbortSignal.timeout(15_000),
})
const body = await response.json().catch(() => null)
if (!response.ok || typeof body?.id !== "string") {
console.error(`[mail] Resend hat ${type}-Mail abgelehnt (${response.status}):`, body?.message ?? body)
return { ok: false, error: "E-Mail konnte nicht gesendet werden." }
}
return { ok: true, id: body.id }
} catch (error) {
console.error(`[mail] ${type}-Mail fehlgeschlagen:`, error)
return { ok: false, error: "E-Mail konnte nicht gesendet werden." }
}
}