import nodemailer from "nodemailer"; import { queueEmail } from "./email-queue"; // Port 587 = STARTTLS, Port 465 = SSL/TLS const transporter = nodemailer.createTransport({ host: process.env.SMTP_HOST, port: Number(process.env.SMTP_PORT ?? 587), secure: false, auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS, }, connectionTimeout: 15000, greetingTimeout: 10000, socketTimeout: 20000, tls: { rejectUnauthorized: false, ciphers: "SSLv3", }, }); export interface KontaktEmailData { name: string; anrede?: string; telefon?: string; email: string; betreff: string; nachricht?: string; } interface MailOptions { from: string; to: string | undefined; replyTo?: string; subject: string; text: string; html: string; } async function sendWithFallback( options: MailOptions, label: string ): Promise<{ sent: boolean; queued: boolean }> { if (!options.to) { console.error(`[Mailer] Kein Empfänger für "${label}" – Mail übersprungen`); return { sent: false, queued: false }; } try { await transporter.sendMail(options); console.log(`[Mailer] ✓ Mail "${label}" an "${options.to}" gesendet`); return { sent: true, queued: false }; } catch (err) { const msg = err instanceof Error ? err.message : String(err); console.error(`[Mailer] ✗ Mail "${label}" fehlgeschlagen (${msg}) – versuche Queue`); const queued = await queueEmail({ mail_from: options.from, mail_to: options.to, reply_to: options.replyTo, subject: options.subject, html: options.html, body_text: options.text, }); return { sent: false, queued }; } } export async function sendeKontaktEmail( data: KontaktEmailData ): Promise<{ sent: boolean; queued: boolean }> { const anrede = data.anrede ? `${data.anrede.charAt(0).toUpperCase() + data.anrede.slice(1)} ` : ""; const html = `

MBO Tech IT

Neue Kontaktanfrage

Kontaktanfrage von ${anrede}${data.name}

${data.telefon ? `` : ""}
Name${anrede}${data.name}
Telefon${data.telefon}
E-Mail${data.email}
Betreff${data.betreff}
${ data.nachricht ? `

${data.nachricht}

` : "" }

MBO Tech IT · ${process.env.APP_URL ?? "https://mbo-tech-it.de"}

`; return sendWithFallback( { from: `"MBO Tech IT" <${process.env.SMTP_FROM}>`, to: process.env.SMTP_TO, replyTo: data.email, subject: `Kontaktanfrage: ${anrede}${data.name} – ${data.betreff}`, text: `Neue Kontaktanfrage\n\nName: ${anrede}${data.name}${data.telefon ? `\nTelefon: ${data.telefon}` : ""}\nE-Mail: ${data.email}\nBetreff: ${data.betreff}${data.nachricht ? `\n\nNachricht:\n${data.nachricht}` : ""}`, html, }, `Kontaktanfrage ${data.name}` ); }