// controllers/contactController.js const nodemailer = require("nodemailer"); const { body, validationResult } = require("express-validator"); require("dotenv").config(); // Configure the transporter with Gmail SMTP const transporter = nodemailer.createTransport({ service: "gmail", auth: { user: process.env.GMAIL_USER, pass: process.env.GMAIL_PASS, }, }); // Function to send an email const sendEmail = async (to, subject, html) => { try { const mailOptions = { from: process.env.GMAIL_USER, to, subject, html, replyTo: html.includes("replyTo") ? html.replyTo : process.env.GMAIL_USER, }; const info = await transporter.sendMail(mailOptions); console.log("Email sent:", info.response); return info; } catch (error) { console.error("Error sending email:", error); throw error; } }; // Submit contact form handler with integrated validation exports.submitContactForm = async (req, res) => { try { // Run validation first await Promise.all([ body("name") .trim() .notEmpty() .withMessage("Vui lòng nhập họ và tên") .run(req), body("email") .isEmail() .withMessage("Vui lòng nhập email hợp lệ") .run(req), body("phone") .trim() .notEmpty() .withMessage("Vui lòng nhập số điện thoại") .run(req), body("message") .trim() .notEmpty() .withMessage("Vui lòng nhập nội dung tin nhắn") .run(req), ]); // Check for validation errors const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ success: false, message: errors.array()[0].msg, }); } const { name, email, phone, message } = req.body; // Optional: Log contact submission (could be saved to database in real application) console.log(`New contact form submission from ${name} (${email})`); // Format the email content const emailContent = `
${name}
${email}
${phone}
${message}