使用 ejs 和节点创建动态 html

Create dynamic html with ejs and node

我正在尝试将动态邮件发送到使用表单提交的电子邮件 ID。
下面是我的 app.js 代码。

//Importing Packages
var express     = require('express');
var nodemailer  = require('nodemailer');
var bodyParser  = require('body-parser');


//Applying Express,Ejs to Node
app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
//Creating Nodemailer Transport
var transporter = nodemailer.createTransport({
    host: 'smtp.zoho.com',
    port: 465,
    secure: true,
    auth: {
        user: 'noreply@*****.com',
        pass: '******'
    }
});

//Root Route Setup
app.get('/', function(req, res){
    res.render("landing")
});

//Route to send the mail
app.post('/send', function(req,res){
    //Setting up Email settings
    var mailOptions = {
        from: 'noreply@*****.com',
        to : req.body.mail,
        subject: 'Verify Your Email',
        generateTextFromHtml : true,
        html: { path: './tmpl.html'}
    };

    //Execute this to send the mail
    transporter.sendMail(mailOptions, function(error, response){
        if(error) {
            console.log(error);
        } else {
            console.log(response);
        }
    });
    res.send("Mail succesfully sent!")
});

//Server &Port Settings
app.listen(3333, function(){
    console.log("Server is running...")
});

下面是我的Form页面代码,是一个ejs文件

<form action="/send" method="POST">
    <input type="email" name="mail" placeholder="Enter your email">
    <input type="text" name="name" placeholder="Enter your name">
    <input type="submit">
</form>

下面是我的 html 模板,该模板已邮寄到使用表单提交的 ID。

<html>
<body>

    <h1>Hello World!</h1>
    <a href="http://www.google/com">Link</a>

</body>
</html>

如何从表单中读取姓名,然后将其包含在电子邮件中,以便在每封电子邮件中,我都可以使用变量向该人发送地址,例如 "Hello Mr {{name}}"

我无法弄清楚如何将变量传递给 html 文件而不被电子邮件阻止,因为我无法使用 Javascript 在 HTML 中使用脚本标记文件,因为几乎所有的邮件提供商都会在电子邮件中阻止 JS!

有人可以帮我解决这个问题吗?

您可以使用已经通过 express 设置的 ejs 模板引擎。调用 app.render() 会将您指定的模板呈现为字符串并将其传递给它的回调,以及您传递给它的任何数据。所以回调有点难看,但这是一个不添加任何依赖项的解决方案。

简而言之,将您的电子邮件模板设为名为 verifyEmail.ejs 的 ejs 文件, 在从 app.render 回调发送电子邮件之前,使用 app.render() 使用 POST 请求正文中的数据呈现它。


// app.js

app.post('/send', function(req,res){
    // Use the ejs rendering engine to render your email 
    // Pass in the 'name' variable that is used in the template file
    app.render('verifyEmail', {name: req.body.name}, function(err, html){ 
    if (err) {
        console.log('error rendering email template:', err) 
        return
    } else {
    //Setting up Email settings
        var mailOptions = {
            from: 'noreply@*****.com',
            to : req.body.mail,
            subject: 'Verify Your Email',
            generateTextFromHtml : true,
            // pass the rendered html string in as your html 
            html: html 
        };

        //Execute this to send the mail
        transporter.sendMail(mailOptions, function(error, response){
            if(error) {
                console.log(error);
                res.send('Mail Error! Try again')
            } else {
                console.log(response);

                res.send("Mail succesfully sent!")
            }
        });
      } 
    }); 
});

我添加了一些错误处理,并在由于服务器错误而未发送电子邮件时通知用户。您之前调用 res.send() 的方式会告诉用户电子邮件在发送之前已成功发送。


将您的模板文件夹放在与您的 "landing" 模板相同的目录中,或者您的 ejs 文件所在的任何其他地方。

通过调用 <%= %> 标记之间的变量将数据插入模板。在呈现模板时通过传递同名变量来填充它。

来自 ejs docs:

... everything inside <%= %> tags inserts itself into the returned HTML string.

// views/verifyEmail.ejs

<html>
<body>

    <h1>Hello <%= name %></h1>
    <a href="http://www.google/com">Link</a>

</body>
</html>