node-express-boilerplate icon indicating copy to clipboard operation
node-express-boilerplate copied to clipboard

Add handlebars to send the emails

Open Jaydipsinhv opened this issue 3 years ago • 2 comments
trafficstars

@hagopj13

During the review I found important thing missing related with sending emails. Right now boilerplate allowed to send the email with string which we need to update manually. I like to add feature to send the emails using handlebars.

If you think above idea is good then I can start implementing this feature. Happy to discuss more on this if it make sense.

Thanks, JD

Jaydipsinhv avatar Jun 02 '22 12:06 Jaydipsinhv

@Jaydipsinhv That is a good idea if we get this feature in this repo.

sagardspeed2 avatar Jul 20 '22 12:07 sagardspeed2

Just Create a folder named templates in src, put your templates in,

You can use these sites for templates:

https://www.arengu.com/email-templates/magic-link https://mjml.io/try-it-live

// email.service.js
const fs = require('fs');
const path = require('path');
const nodemailer = require('nodemailer');
const Handlebars = require('handlebars');

const config = require('../config/config');
const logger = require('../config/logger');

const emailsDir = path.resolve(process.cwd(), 'src/templates');

const transport = nodemailer.createTransport(config.email.smtp);
/* istanbul ignore next */
if (config.env !== 'test') {
  transport
    .verify()
    .then(() => logger.info('Connected to email server'))
    .catch(() => logger.warn('Unable to connect to email server. Make sure you have configured the SMTP options in .env'));
}

/**
 * Send reset password email
 * @param {string} to
 * @param {string} token
 * @returns {Promise}
 */
const sendResetPasswordEmail = async (to, token) => {
  // eslint-disable-next-line security/detect-non-literal-fs-filename
  const emailFile = fs.readFileSync(path.join(emailsDir, 'reset.template.html'), {
    encoding: 'utf8',
  });
  const emailTemplate = Handlebars.compile(emailFile);

  const resetPasswordUrl = `${config.app.url}/reset-password?token=${token}`;

  await transport.sendMail({
    from: `${config.app.name} ${config.email.from}`,
    to,
    subject: `Reset Password - ${config.app.name}`,
    html: emailTemplate({
      APP_NAME: config.app.name,
      APP_LOGO: config.app.logo,
      APP_COLOR: config.app.color,
      RESET_PASSWORD_URL: resetPasswordUrl,
    }),
  });
};

config.app...... refers to FRONTEND APP's URL, LOGO, NAME

0darkace1 avatar Sep 12 '23 18:09 0darkace1