Using HTML Templates

If you need to send dynamic HTML emails, consider using templating engines like Handlebars or EJS. Here’s how you might use Handlebars with Nodemailer:

Install the required packages:

npm install handlebars nodemailer-express-handlebars

Set up Nodemailer with Handlebars:

const nodemailer = require('nodemailer');
const path = require('path');
const hbs = require('nodemailer-express-handlebars');

// Create a transporter object
let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS
    }
});

// Set up Handlebars
transporter.use('compile', hbs({
    viewEngine: {
        extName: '.hbs',
        partialsDir: path.resolve('./views/'),
        layoutsDir: path.resolve('./views/'),
        defaultLayout: 'email'
    },
    viewPath: path.resolve('./views/'),
    extName: '.hbs'
}));

// Email options
let mailOptions = {
    from: '"Your Name" <your-email@gmail.com>',
    to: 'recipient@example.com',
    subject: 'Hello with Handlebars',
    template: 'email', // Name of the template file (email.hbs)
    context: { // Data to pass to the template
        name: 'Recipient',
        message: 'This is a test email using Handlebars!'
    }
};

// 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/email.hbs):

<!DOCTYPE html>
<html>
<head>
    <title>{{subject}}</title>
</head>
<body>
    <h1>Hello, {{name}}!</h1>
    <p>{{message}}</p>
</body>
</html>

Comments

Leave a Reply

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