import nodemailer from 'nodemailer'; /** * Creates and returns a nodemailer SMTP transporter using environment variables. */ export function createSmtpTransporter() { const host = process.env.SMTP_HOST; const port = parseInt(process.env.SMTP_PORT || '465', 10); const secure = process.env.SMTP_SECURE === 'true' || port === 465; const user = process.env.SMTP_USER; const pass = process.env.SMTP_PASS; if (!host || !user || !pass) { return null; } return nodemailer.createTransport({ host, port, secure, auth: { user, pass }, tls: { rejectUnauthorized: false } }); } /** * Sends a contact form email via SMTP using nodemailer. */ export async function sendContactEmail({ name, email, phone, subject, message }) { const transporter = createSmtpTransporter(); const toEmail = process.env.SMTP_TO || process.env.SMTP_USER || 'info@cavinfotech.com'; const fromEmail = process.env.SMTP_FROM || `"Cavin Infotech Contact Form" <${process.env.SMTP_USER || 'info@cavinfotech.com'}>`; const mailSubject = `[Contact Inquiry] ${subject ? subject : `New Inquiry from ${name}`}`; const htmlContent = `

Cavin Infotech

New Website Contact Form Inquiry

Name: ${name}
Email: ${email}
Phone No: ${phone || 'Not provided'}
Subject: ${subject || 'General Inquiry'}

Message:

${message}

Submitted on ${new Date().toLocaleString()} from Cavin Infotech Contact Us Page
`; const textContent = ` New Contact Inquiry - Cavin Infotech Name: ${name} Email: ${email} Phone: ${phone || 'Not provided'} Subject: ${subject || 'General Inquiry'} Message: ${message} Submitted on: ${new Date().toLocaleString()} `; if (!transporter) { console.warn('[SMTP Service] SMTP credentials not set in environment (SMTP_HOST, SMTP_USER, SMTP_PASS).'); return { success: false, error: 'SMTP credentials not configured on the server. Please set SMTP_HOST, SMTP_USER, and SMTP_PASS in .env file.' }; } try { const info = await transporter.sendMail({ from: fromEmail, to: toEmail, replyTo: `"${name}" <${email}>`, subject: mailSubject, text: textContent, html: htmlContent }); console.log('[SMTP Service] Contact email sent via SMTP:', info.messageId); return { success: true, messageId: info.messageId }; } catch (err) { console.error('[SMTP Service] Failed to send email via SMTP:', err); return { success: false, error: err.message || 'SMTP sending failed' }; } }