import nodemailer from 'nodemailer'; export default async function handler(req, res) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); if (req.method === 'OPTIONS') { return res.status(200).end(); } if (req.method !== 'POST') { return res.status(405).json({ error: 'Method Not Allowed' }); } const { type, name, email, phone, mobile, subject, message, interests, turnstileToken } = req.body; const contactName = name?.trim(); const contactEmail = email?.trim(); const contactPhone = (phone || mobile || '').trim(); const contactSubject = (subject || interests || type || 'General Inquiry').trim(); const contactMessage = (message || req.body.comments || '').trim(); if (!contactName || !contactEmail) { return res.status(400).json({ error: 'Name and Email are required.' }); } // Verify Cloudflare Turnstile Token if (turnstileToken) { const secretKey = process.env.TURNSTILE_SECRET_KEY || '1x000000000000000000000000000000AA'; try { const formData = new URLSearchParams(); formData.append('secret', secretKey); formData.append('response', turnstileToken); const turnstileRes = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { method: 'POST', body: formData }); const turnstileOutcome = await turnstileRes.json(); if (!turnstileOutcome.success) { return res.status(400).json({ error: 'Cloudflare Turnstile verification failed. Please try again.' }); } } catch (err) { console.error('Turnstile verification error:', err); } } // 1. Try sending via SMTP (nodemailer) const smtpHost = process.env.SMTP_HOST; const smtpUser = process.env.SMTP_USER; const smtpPass = process.env.SMTP_PASS; if (smtpHost && smtpUser && smtpPass) { try { const port = parseInt(process.env.SMTP_PORT || '465', 10); const secure = process.env.SMTP_SECURE === 'true' || port === 465; const transporter = nodemailer.createTransport({ host: smtpHost, port, secure, auth: { user: smtpUser, pass: smtpPass }, tls: { rejectUnauthorized: false } }); const toEmail = process.env.SMTP_TO || smtpUser; const fromEmail = process.env.SMTP_FROM || `"Cavin Infotech Contact" <${smtpUser}>`; const info = await transporter.sendMail({ from: fromEmail, to: toEmail, replyTo: `"${contactName}" <${contactEmail}>`, subject: `[Contact Form] ${contactSubject}`, text: `Name: ${contactName}\nEmail: ${contactEmail}\nPhone: ${contactPhone}\nSubject: ${contactSubject}\n\nMessage:\n${contactMessage}`, html: `
Name: ${contactName}
Email: ${contactEmail}
Phone: ${contactPhone || 'Not provided'}
Subject: ${contactSubject}
${contactMessage}