MBO-Tech-IT-Webseite/app/api/admin/smtp-test/route.ts

69 lines
2.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { NextResponse } from "next/server";
import nodemailer from "nodemailer";
export const dynamic = "force-dynamic";
// Optionaler Schutz via ADMIN_SECRET env-Variable.
// Wird durch lib/admin-auth ersetzt wenn Modul 02-admin-auth integriert ist.
function checkAuth(request: Request): NextResponse | null {
const secret = process.env.ADMIN_SECRET;
if (!secret) return null;
const auth = request.headers.get("authorization");
if (auth !== `Bearer ${secret}`) {
return NextResponse.json({ error: "Nicht autorisiert" }, { status: 401 });
}
return null;
}
export async function GET(request: Request) {
const authError = checkAuth(request);
if (authError) return authError;
const config = {
host: process.env.SMTP_HOST ?? "(nicht gesetzt)",
port: Number(process.env.SMTP_PORT ?? 587),
user: process.env.SMTP_USER ?? "(nicht gesetzt)",
from: process.env.SMTP_FROM ?? "(nicht gesetzt)",
to: process.env.SMTP_TO ?? "(nicht gesetzt)",
};
const transport = nodemailer.createTransport({
host: config.host,
port: config.port,
secure: false,
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
connectionTimeout: 10000,
greetingTimeout: 8000,
socketTimeout: 12000,
tls: { rejectUnauthorized: false },
});
try {
await transport.verify();
await transport.sendMail({
from: `"MBO Tech IT TEST" <${process.env.SMTP_FROM}>`,
to: process.env.SMTP_TO,
subject: `✓ SMTP-Test erfolgreich ${new Date().toLocaleString("de-DE")}`,
text: "Diese Test-Mail wurde automatisch von /api/admin/smtp-test gesendet.\n\nSMTP-Verbindung und Mail-Versand funktionieren korrekt.",
html: `<p style="font-family:sans-serif">Test von <code>/api/admin/smtp-test</code></p><p style="color:green;font-weight:bold">✓ SMTP-Verbindung und Mail-Versand funktionieren korrekt.</p>`,
});
return NextResponse.json({
ok: true,
message: "SMTP-Verbindung erfolgreich Test-Mail gesendet",
config: { ...config, pass: "***" },
});
} catch (err) {
const e = err as Error & { code?: string; command?: string };
return NextResponse.json(
{
ok: false,
error: e.message,
code: e.code,
command: e.command,
config: { ...config, pass: "***" },
},
{ status: 500 }
);
}
}