import type { ReactNode } from "react"; import { Resend } from "resend"; let resendClient: Resend | null = null; type SendAppEmailInput = { to: string | string[]; subject: string; react: ReactNode; from?: string; replyTo?: string | string[]; idempotencyKey?: string; }; type SendAppEmailResult = | { success: true; id?: string } | { success: false; error: string }; export function getAppEmailConfigError() { if (process.env.NODE_ENV === "development") { return null; } if (!process.env.RESEND_API_KEY) { return "E-Mail-Versand ist derzeit nicht verfügbar."; } if (!process.env.EMAIL_FROM) { return "E-Mail-Versand ist derzeit nicht verfügbar."; } return null; } export async function sendAppEmail({ to, subject, react, from = process.env.EMAIL_FROM, replyTo, idempotencyKey, }: SendAppEmailInput): Promise { if (Array.isArray(to)) { let id: string | undefined; for (const recipient of new Set(to)) { const result = await sendAppEmail({ to: recipient, subject, react, from, replyTo }); if (!result.success) return result; id = result.id; } return { success: true, id }; } if (!process.env.RESEND_API_KEY) { if (process.env.NODE_ENV === "development") { console.log("\n✉️ [DEV EMAIL SIMULATION]"); console.log(`From: ${from || "not-configured"}`); console.log(`To: ${Array.isArray(to) ? to.join(", ") : to}`); console.log(`Subject: ${subject}`); console.log("-----------------------------------------"); console.log("Email body react element is rendered."); console.log("=========================================\n"); return { success: true, id: "dev-simulated-id" }; } return { success: false, error: "E-Mail-Versand ist derzeit nicht verfügbar.", }; } if (!from) { return { success: false, error: "E-Mail-Versand ist derzeit nicht verfügbar.", }; } try { resendClient ??= new Resend(process.env.RESEND_API_KEY); const { data, error } = await resendClient.emails.send( { from: from!, to, subject, react, replyTo, }, { idempotencyKey }, ); if (error) { console.error("Resend konnte die E-Mail nicht versenden:", error); return { success: false, error: "E-Mail-Versand fehlgeschlagen.", }; } return { success: true, id: data?.id }; } catch (error) { console.error("Unerwarteter Fehler beim E-Mail-Versand:", error); return { success: false, error: "E-Mail-Versand fehlgeschlagen.", }; } }