const { google } = require('googleapis'); const { oAuth2Client } = require('../config/googleOAuth'); const sendEmail = async (recipient, subject, htmlContent, attachment = null, attachmentName = '') => { try { const gmail = google.gmail({ version: 'v1', auth: oAuth2Client }); // Unique boundary string const boundary = "----=_NextPart_001"; let rawEmail = [ `To: ${recipient}`, `Subject: ${subject}`, `MIME-Version: 1.0`, ]; if (attachment && attachment.buffer) { const encodedAttachment = Buffer.isBuffer(attachment.buffer) ? attachment.buffer.toString('base64') : Buffer.from(attachment.buffer).toString('base64'); const formattedAttachment = encodedAttachment.match(/.{1,76}/g).join("\n"); rawEmail.push( `Content-Type: multipart/mixed; boundary="${boundary}"`, "", `--${boundary}`, "Content-Type: text/html; charset=UTF-8", "", htmlContent, "", `--${boundary}`, `Content-Type: ${attachment.mimetype}; name="${attachmentName}"`, `Content-Disposition: attachment; filename="${attachmentName}"`, "Content-Transfer-Encoding: base64", "", formattedAttachment, "", `--${boundary}--` ); } else { rawEmail.push("Content-Type: text/html; charset=UTF-8", "", htmlContent); } const encodedEmail = Buffer.from(rawEmail.join("\r\n")) .toString("base64") .replace(/\+/g, "-") .replace(/\//g, "_") .replace(/=+$/, ""); // Remove padding `=` characters await gmail.users.messages.send({ userId: "me", requestBody: { raw: encodedEmail }, }); console.log(`✅ Email sent successfully to ${recipient}`); } catch (error) { console.log(`❌ Failed to send email to ${recipient}:`, error); throw error; } }; module.exports = { sendEmail };