【问题标题】:NodeJS and express How to send variables with the template when sending emails using nodemailerNodeJS 和 express 使用 nodemailer 发送电子邮件时如何使用模板发送变量
【发布时间】:2020-11-07 03:40:24
【问题描述】:

我正在使用nodemailer 为注册用户发送电子邮件。函数如下:

const setAndSendMsg = (recipients, users, subject, template) => {
    const htmlFile = checkTemplate(template)
    const message = {
        from: mailServer.mailerObj.auth.user,
        bcc: recipients,
        subject: subject,
        // html: `<div><b>Hello</b></div>`,
        html: htmlFile,       
        context: {
            user: 'test'
        }
    }

    transport.sendMail(message, function(err, data) {
        if(err) {
            console.log(err);
            return err
        } else {
            console.log(data);
            return data
        }
    })
}

checkTemplate返回所需模板:

const checkTemplate = (template) => {
    return fs.readFileSync(path.resolve(__dirname, `../email-templates/${template}.html`), 'utf-8').toString()
}

模板包含:

<div>
    Dear {{user}},
    <br/>
    <div>
        Welcome to our platform, please click on the link below to activate your account:
        
    </div>
</div>

所有收件人都收到了这封电子邮件,如下所示:

亲爱的{{user}},...

没有显示test 代替{{user}}

我在 stackoverflow 上使用了来自 question 的脚本,但它不起作用。

【问题讨论】:

  • 你使用的模板引擎是什么?
  • @Bibek 普通 html

标签: node.js express nodemailer


【解决方案1】:

问题出在您的配置中,您将模板定义为静态 html,因此没有评估变量,如果您转到 node-mailer here 的模板文档,您会发现不再支持,而是他们向您发送here。我的建议是遵循官方文档,那里提供了很好的示例。

另一种方法是将模板手动呈现为静态 html 并将其设置为邮件程序,如果您不想安装另一个包,但 email-templates 会为您执行此操作:)

希望这会有所帮助。

干杯:)

【讨论】:

    猜你喜欢
    • 2018-07-11
    • 2016-07-18
    • 1970-01-01
    • 2015-05-19
    • 2022-06-13
    • 2018-07-14
    相关资源
    最近更新 更多