import nodemailer from "nodemailer";
function confirmationTemplate(name: string) {
return `
Thanks for reaching out!
I will make my best to read your message as soon as possible!
This is just a confirmation — no need to reply to this email.
© ${new Date().getFullYear()} 4l3ks.com
`;
}
async function verifyRecaptcha(token: string) {
const res = await fetch(
"https://www.google.com/recaptcha/api/siteverify",
{
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `secret=${process.env.RECAPTCHA_SECRET_KEY}&response=${token}`,
}
);
return res.json();
}
export async function POST(req: Request) {
try {
const { name, email, subject, message, token } = await req.json();
if (!process.env.RECAPTCHA_SECRET_KEY) {
throw new Error("Missing RECAPTCHA_SECRET_KEY");
}
if (!token) {
return Response.json(
{ success: false, error: "Missing captcha token" },
{ status: 400 }
);
}
const captcha = await verifyRecaptcha(token);
if (!captcha || captcha.success !== true) {
console.warn("Captcha failed:", captcha);
return Response.json(
{ success: false, error: "Captcha failed" },
{ status: 403 }
);
}
// ✅ 2. ONLY NOW send emails
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST!,
port: Number(process.env.SMTP_PORT),
secure: false,
auth: {
user: process.env.SMTP_USER!,
pass: process.env.SMTP_PASS!,
},
});
// Admin email
await transporter.sendMail({
from: `"Contact Form" <${process.env.SMTP_USER!}>`,
to: process.env.CONTACT_EMAIL!,
replyTo: email,
subject: subject || `New message from ${email}`,
html: `