Files
citpl_cms_react_express_pos…/api/send.js
T

128 lines
4.9 KiB
JavaScript

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: `
<div style="font-family: Arial, sans-serif; background: #020710; color: #fff; padding: 30px; border-radius: 12px;">
<h2 style="color: #ffaa00; margin-top: 0;">Cavin Infotech - Contact Inquiry</h2>
<p><strong>Name:</strong> ${contactName}</p>
<p><strong>Email:</strong> <a href="mailto:${contactEmail}" style="color: #38bdf8;">${contactEmail}</a></p>
<p><strong>Phone:</strong> ${contactPhone || 'Not provided'}</p>
<p><strong>Subject:</strong> ${contactSubject}</p>
<div style="margin-top: 20px; padding: 15px; background: #0b1528; border-left: 4px solid #ffaa00; border-radius: 6px;">
<p style="margin: 0; white-space: pre-line;">${contactMessage}</p>
</div>
</div>
`
});
return res.status(200).json({ success: true, messageId: info.messageId, message: 'Message sent via SMTP!' });
} catch (smtpErr) {
console.error('SMTP Send Error:', smtpErr);
return res.status(500).json({ error: `SMTP Send Error: ${smtpErr.message}` });
}
}
// 2. Fallback to EmailJS API if SMTP env vars are not set
const serviceId = process.env.EMAILJS_SERVICE_ID || 'vishva_cavintest';
const publicKey = process.env.EMAILJS_PUBLIC_KEY || 'YOUR_EMAILJS_PUBLIC_KEY';
const templateId = process.env.EMAILJS_TEMPLATE_ID_STRATEGY || 'YOUR_EMAILJS_TEMPLATE_ID_STRATEGY';
try {
const response = await fetch('https://api.emailjs.com/api/v1.0/email/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
service_id: serviceId,
template_id: templateId,
user_id: publicKey,
template_params: {
name: contactName,
email: contactEmail,
phone: contactPhone,
interests: contactSubject,
message: contactMessage
}
}),
});
const data = await response.text();
if (!response.ok) {
return res.status(response.status).json({ error: data });
}
return res.status(200).json({ success: true, message: data });
} catch (error) {
return res.status(500).json({ error: error.message });
}
}