首页 > 解决方案 > 使用节点 js 将函数参数值发送到 html 模板

问题描述

我正在 node.js 中编写服务。在那,我曾经使用验证链接将邮件发送给用户。为此,我使用了 nodemailer,一切正常。在那,我直接使用了 html 部分,所以我访问了 token 变量。现在我需要将该 html 部分移动到单独的文件夹中。现在问题是访问令牌(即参数值)我的代码就像,modules/users.js

let sendNotification = await mailer.sendMail(userDetail.email, token);  

当我创建用户时,令牌被发送到 userDetail.email。我以前的邮件程序看起来像 mailer/applicationMailer.js

async function sendMail(userMail, token) {
// let htmlTemplate = fs.readFileSync(__dirname + '/templates/mail.html');
let transporter = nodemailer.createTransport(smtpTransport({
    host: 'smtp.gmail.com',
    port: 587,
    secure: false,
    auth: {
        user: 'xxx@gmail.com',
        pass: '********'
    }
}));

let mailOptions = {
    from: 'xxx@gmail.com',
    to: userMail,
    cc: '',
    subject: 'Account verification',
    // html: htmlTemplate
    html: `<p>To verify your account click <a href="https://employee-attendance-service.herokuapp.com/users/verify?token=${token}">LINK</a></p>` +
            `<p>This link will be expired in two days.</p>` + 
            `<p><strong>Note:</strong> Contact your ADMIN, if the link is expired</p>`
};

transporter.sendMail(mailOptions, async function (error, info) {
    if (error) {
        console.log(error);
    } else {
        console.log('Email sent: ' + info.response);
    }
});
};  

我需要将 html 部分移动到 template/mail.html 并访问 htmlTemplate 变量。在那里我无法访问令牌。我需要将参数值传递给 html 页面。怎么做?
提前致谢。

标签: htmlnode.jsnodemailer

解决方案


您正在寻找EJS

const ejs = require("ejs");

ejs.renderFile(__dirname + "/test.ejs", { token }, function (err, data) {
    if (err) {
        console.log(err);
    } else {
    const mainOptions = {
             from: 'xxx@gmail.com',
             to: userMail,
             cc: '',
             subject: 'Account verification',    
            html: data
        };


        transporter.sendMail(mainOptions, function (err, info) {
            if (err) {
                console.log(err);
            } else {
                console.log('Message sent: ' + info.response);
            }
        });
    }

    });

推荐阅读