gpt4 book ai didi

node.js - 如何在nodejs中外部使用html文件(不是内部html)?

转载 作者:太空宇宙 更新时间:2023-11-04 00:00:58 25 4
gpt4 key购买 nike

我想使用nodejs发送多封邮件。目前我正在 Route 的 Nodejs 脚本中使用 html 代码。但是当 html 变大时,Nodejs 文件也会变大,并且不具有可维护性。

那么如何在外部使用 html 文件呢?

我在外部使用nodemailer代码。像这样,我也想在外部使用 html 文件(/api/htmls/registerEmail.html)。但是 html 文件也使用主体数据 (req.body.fname)

ma​​ilSender.js (/api/routes/r_msg/)

var nodemailer = require('nodemailer');

function sendMail(to, msg, subject)
{

var transporter = nodemailer.createTransport({

host: 'smtp.zoho.com',
port: 465,
secure: true,
auth: {
user: 'sample@sample.com',
pass: 'password'
}
});

var mailOptions = {
from: 'sample@sample.com',
to:to,
subject: subject,
html: msg,
};

transporter.sendMail(mailOptions, function(error, info)
{
if (error)
{
console.log(error);
}
})

}

module.exports.sendMail = sendMail;

register.js (/api/routes/)

const express = require('express');
const router = express.Router();
const app = express();
const sendMail = require("../api/routes/r_msg");

router.post("/register/new", (req, res) =>
{
const newStudent = new Student(
{
fname: req.body.fname,
lname: req.body.lname,
contact_no: req.body.lname,
email : req.body.email
});

newStudent.save()
.then(student =>
{
if (student)
{
//This line want to change
var html = `<html> <body> Hello ` + req.body.fname + `Welcome </body> </html>`;

sendMail.sendMail(req.body.email, html, 'Success');
res.status(200).send(setting.status("Success")
console.log('Email sent: ' + info.response);
}

});
}

最佳答案

正如评论中提到的,您可以使用 ejs 来解决它.

将此添加到您的register.js:

const ejs = require('ejs');
const promisify = require('util').promisify;
const renderFile = promisify(ejs.renderFile);

// inside route handler:

renderFile(__dirname + "/api/htmls/registerEmail.html", {fname: req.body.fname})
.then(html => {
sendMail.sendMail(req.body.email, html, 'Success');
})
.catch(error => {
// handle error
})

电子邮件模板registerEmail.html

<html> <body> Hello <%= fname %> Welcome </body> </html>

关于node.js - 如何在nodejs中外部使用html文件(不是内部html)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54711682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com