import { mailOptions, transporter } from "@/lib/nodemailer/nodemailer"; import { NextRequest, NextResponse } from "next/server"; const CONTACT_MESSAGE_FIELDS: Record = { name: "Name", email: "Email", message: "Message" }; const escapeHtml = (text: string) => { return text .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); }; const generateEmailContent = (data: Record) => { const stringData = Object.entries(data).reduce( (str, [key, val]) => str + `${CONTACT_MESSAGE_FIELDS[key] || key}: ${val.replace(/\n/g, "\n")} \n\n`, "" ); const htmlData = Object.entries(data).reduce( (str, [key, val]) => str + `

${escapeHtml( CONTACT_MESSAGE_FIELDS[key] || key )}

${escapeHtml(val).replace( /\n/g, "
" )}

`, "" ); return { text: stringData, html: ` Contact Email

New Contact Message

${htmlData}
` }; }; export async function POST(req: NextRequest) { if (req.method !== "POST") { return NextResponse.json( { message: "Method Not Allowed" }, { status: 405 } ); } try { const data = await req.json(); console.log(data); await transporter.sendMail({ ...mailOptions, ...generateEmailContent(data), subject: "Contact Email" }); return NextResponse.json( { message: "Email sent successfully" }, { status: 200 } ); } catch (error) { console.error("Error sending email:", error); return NextResponse.json( { message: "Internal Server Error" }, { status: 500 } ); } }