For more dynamic content within email templates, you can use template engines with placeholders. For instance, you can use Handlebars or Pug for advanced templating.
Example with Handlebars and Nodemailer:
Install Handlebars:
npm install handlebars nodemailer-express-handlebars
Set Up Handlebars:
const nodemailer = require('nodemailer');
const hbs = require('nodemailer-express-handlebars');
const path = require('path');
// Create a transporter object
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS
}
});
// Configure Handlebars
transporter.use('compile', hbs({
viewEngine: {
extName: '.hbs',
layoutsDir: path.resolve('./views/'),
defaultLayout: 'template',
},
viewPath: path.resolve('./views/'),
extName: '.hbs'
}));
// Email options
let mailOptions = {
from: '"Your Name" <[email protected]>',
to: '[email protected]',
subject: 'Welcome!',
template: 'welcome', // 'welcome.hbs'
context: {
name: 'John Doe',
activationLink: 'https://example.com/activate?token=123456'
}
};
// Send email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.error('Error sending email:', error);
}
console.log('Email sent successfully:', info.response);
});
Template File (views/welcome.hbs
):
<!DOCTYPE html>
<html>
<head>
<title>Welcome {{name}}</title>
</head>
<body>
<h1>Welcome, {{name}}!</h1>
<p>Please activate your account by clicking <a href="{{activationLink}}">here</a>.</p>
</body>
</html>
Leave a Reply