Handlebars 作为电子邮件模板

Handlebars as an email template

我刚刚继承了一个代码库,它使用 handlebars 作为电子邮件模板语言。

我已经四处搜索以尝试获取更多信息,但找不到其他人这样做。

我只是想知道是否有人可以提供一些文档或搜索词供我查找。我不知道你甚至可以使用这样的车把!

谢谢,

奥利


电子邮件发件人

// Send new account email 
function sendNewAccountEmail(expert) {   
  ...
  return handlebars.render('views/emails/newAccountEmail.handlebars', {
    name: `${expert.firstName} ${expert.lastName}`,
    layout: false,
    expert,
    url: `${LIVE_URL}/expert/reset/${expert.resetPasswordToken}`,   
}).then(email => new Promise((resolve, reject) => {
      sendmail({
        from: SEND_EMAIL,
        to: recipient,
        subject: '',
        text: email,
      }, (err, reply) => {
        ...
      });
    })); }

newAccountEmail.handlebars

Hi {{name}},

You now have access to RARA Survey tool!
You can now access your dashboard and assigned campaigns by going to the following link and creating a password:

Login URL: {{url}}

Thanks!

Influencer Team

记住 handlebars 只是一种模板语言。您的代码正在做的是采用 .handlebars 模板,传递一些将填充到您的模板中的变量并将其编译为 html,这是您的 email 变量。然后,您使用 email html 并使用 sendmail 函数实际发送电子邮件。您可以查看完整文档 here

要以文件.hbs为模板发送邮件,需要使用npm包安装:

  1. nodemailer
  2. nodemailer-express-handlebars

将设置主机信息:

    var transport = nodemailer.createTransport({
        host: 'YOUR HOST',
        port: 'YOUR PORT',
        auth: {
            user: 'YOUR USER',
            pass: 'YOUR PASSWORD'
        },
        tls: {
            rejectUnauthorized: false
        }
    });

现在,我们需要配置传输才能使用模板:

    transport.use('compile', hbs({    
        viewPath: 'YOUR PATH where the files are, for example /app/view/email',
        extName: '.hbs'
    }));



    exports.sendEmail = function (from, to, subject, callback) {

        var email = {
            from: 'YOUR FROM FOR EXAMPLE YOU@GMAIL.COM',
            to: 'RECIPIENT',
            subject: 'SUBJECT',
            template: 'TEMPLATE NAME, DO NOT NEED TO PLACE  .HBS',
            context: {
                name: 'YOUR NAME',
                url: 'YOUR URL'
            }
        };

        transport.sendMail(email, function (err) {
            if (err) {
                return callback({ 'status': 'error', 'erro': err });
            }
            else {
                return callback({ 'status': 'success' });
            }
        })
    };