Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 42 additions & 15 deletions app/api/contact/route.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,44 @@
import nodemailer from "nodemailer";

function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(String(email).trim());
}

function escapeHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#x27;');
}

export async function POST(req) {
try {
const { name, email, subject, message } = await req.json();

// Create transporter
// Validate required fields
if (!name || !email || !subject || !message) {
return new Response(
JSON.stringify({ message: "All fields are required" }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}

// Validate email format
if (!isValidEmail(email)) {
return new Response(
JSON.stringify({ message: "Invalid email address format" }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}

// Truncate fields to reasonable lengths
const safeName = escapeHtml(String(name).substring(0, 200));
const safeSubject = escapeHtml(String(subject).substring(0, 200));
const safeMessage = escapeHtml(String(message).substring(0, 5000));

const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
Expand All @@ -13,28 +47,21 @@ export async function POST(req) {
},
});

// Email options
const mailOptions = {
from: email,
from: process.env.EMAIL_USER,
to: process.env.EMAIL_USER,
subject: `New Contact Form Submission: ${subject}`,
text: `
Name: ${name}
Email: ${email}
Subject: ${subject}
Message: ${message}
`,
subject: `New Contact Form Submission: ${safeSubject}`,
text: `Name: ${safeName}\nEmail: ${email}\nSubject: ${safeSubject}\nMessage: ${safeMessage}`,
html: `
<h2>New Contact Form Submission</h2>
<p><strong>Name:</strong> ${name}</p>
<p><strong>Email:</strong> ${email}</p>
<p><strong>Subject:</strong> ${subject}</p>
<p><strong>Name:</strong> ${safeName}</p>
<p><strong>Email:</strong> ${escapeHtml(email)}</p>
<p><strong>Subject:</strong> ${safeSubject}</p>
<p><strong>Message:</strong></p>
<p>${message.replace(/\n/g, "<br>")}</p>
<p>${safeMessage.replace(/\n/g, "<br>")}</p>
`,
};

// Send email
await transporter.sendMail(mailOptions);

return Response.json({ message: "Email sent successfully" });
Expand Down