Skip to content

Instantly share code, notes, and snippets.

@Octagon-simon
Created March 8, 2024 17:17
Show Gist options
  • Save Octagon-simon/e92b43e324f0c3b8c417fd11f288fdb8 to your computer and use it in GitHub Desktop.
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.
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: 'MailingHost@server.com',
port: 465,
auth: {
user: 'user@domain.com',
pass: 'passForUser@domain.com'
}
});
const mailOptions = {
from: 'user@domain.com',
replyTo: 'user@domain.com',
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: 'test@tester.com'
}
//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