Created
March 8, 2024 17:17
Revisions
-
Octagon-simon created this gist
Mar 8, 2024 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,64 @@ import fs from 'fs'; import nodemailer from 'nodemailer'; async function sendEmail(data) { try { //destructure const { dataToReplace, emailSubject, recipientEmail } = data; // Replace with the actual path to your template file const templatePath = `./templates/loginTemplate`; // Read the template file let templateContent = fs.readFileSync(templatePath, 'utf8'); // Replace placeholders with actual values Object.entries(dataToReplace).forEach(([placeholder, value]) => { const regex = new RegExp(`{{${placeholder}}}`, 'g'); templateContent = templateContent.replace(regex, value); }); const transporter = nodemailer.createTransport({ host: '[email protected]', port: 465, auth: { user: '[email protected]', pass: '[email protected]' } }); const mailOptions = { from: '[email protected]', replyTo: '[email protected]', to: recipientEmail, subject: emailSubject, html: templateContent }; //send the email const info = await transporter.sendMail(mailOptions); //return response return info.response; } catch (error) { console.log(error); } } //construct the payload object const emailPayload = { dataToReplace: { username: 'Octagon', ipAddress: '127.0.0.1', location: 'Lagos, Nigeria' }, emailSubject: 'Account Login Notification', recipientEmail: '[email protected]' } //handle Promise with .then sendEmail(emailPayload) .then((res) => console.log(res)) .catch((err) => console.log(err)) //or use await await sendEmail(emailPayload)