Sending ejs template using nodemailer

前端 未结 2 1906
灰色年华
灰色年华 2021-02-01 22:40

I\'m trying to build a web application using express.js. In my application, I\'m using nodemailer for sending mail. If I just use it to send basic mail it work ok; however, when

2条回答
  •  猫巷女王i
    2021-02-01 22:52

    The problem is sendMail gets executed before the fs.readFile gets completed.

    Actually, the readFile can be replaced with ejs.renderFile which reads file and renders the HTML string. Please try the below refactored code.

    var fs = require("fs");
    var nodemailer = require("nodemailer");
    var ejs = require("ejs");
    var transporter = nodemailer.createTransport({
        host: 'smtp.zoho.com',
        port: 465,
        secure: true, // use SSL
        auth: {
            user: 'testmail@zoho.com',
            pass: '123456'
        }
    });
    
    ejs.renderFile(__dirname + "/test.ejs", { name: 'Stranger' }, function (err, data) {
    if (err) {
        console.log(err);
    } else {
        var mainOptions = {
            from: '"Tester" testmail@zoho.com',
            to: "totest@zoho.com",
            subject: 'Hello, world',
            html: data
        };
        console.log("html data ======================>", mainOptions.html);
        transporter.sendMail(mainOptions, function (err, info) {
            if (err) {
                console.log(err);
            } else {
                console.log('Message sent: ' + info.response);
            }
        });
    }
    
    });
    

提交回复
热议问题