在nodemailer中将变量传递给HTML页面可以通过使用模板引擎来实现。以下是一种常见的方法:
npm install ejs
const ejs = require('ejs');
<!DOCTYPE html>
<html>
<head>
<title>Email Template</title>
</head>
<body>
<h1>Welcome <%= username %>!</h1>
<p>Your email address is: <%= email %></p>
</body>
</html>
const nodemailer = require('nodemailer');
// 创建一个SMTP传输对象
const transporter = nodemailer.createTransport({
// 配置SMTP服务器
});
// 定义要发送的邮件内容
const mailOptions = {
from: 'sender@example.com',
to: 'recipient@example.com',
subject: 'Welcome to My Website',
// 使用ejs模板引擎渲染HTML模板
html: ejs.renderFile('template.html', { username: 'John', email: 'john@example.com' })
};
// 发送邮件
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
在上述代码中,我们使用ejs的renderFile
方法来渲染HTML模板,并将变量username
和email
传递给模板。然后,将渲染后的HTML作为html
属性的值传递给mailOptions
对象。
请注意,这只是一种实现方式,你也可以选择其他模板引擎或方法来实现类似的功能。
领取专属 10元无门槛券
手把手带您无忧上云