Created
March 8, 2024 17:17
-
-
Save Octagon-simon/e92b43e324f0c3b8c417fd11f288fdb8 to your computer and use it in GitHub Desktop.
This is a code snippet that you could use to send dynamic emails to your clients in NodeJS using NodeMailer.
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 characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment