My Blog

My WordPress Blog

My Blog

My WordPress Blog

Email Templates with Dynamic Content

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>
&lt;title>Welcome {{name}}&lt;/title>
</head> <body>
&lt;h1>Welcome, {{name}}!&lt;/h1>
&lt;p>Please activate your account by clicking &lt;a href="{{activationLink}}">here&lt;/a>.&lt;/p>
</body> </html>
Email Templates with Dynamic Content

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top