How can I dynamically populate html data in node for posting, not displaying?

804 views Asked by At

I'm currently trying to populate html data in a file stream so that I can send it in an email using smtpTransport. I've tried to use ejs but almost every example I'm seeing is using ejs.render to display the content while I'm trying to further send it along as a string. I want to do this manually versus using something like mail chimp but I haven't found anything too helpful yet. For context, I'm trying to create a receipt email when a user buys something and populate a table with the items. Here's the code that I've been trying to use with ejs but get a "TypeError: this.templateText.replace is not a function error":

router.post('/placeorder', function(req, res) {
    var orderInfo = req.body;

    var delivery = orderInfo.deliveryDate.split("00:00:00")[0] + " from " + orderInfo.deliveryTime;

    //Email buyer receipt
    fs.readFile('buyer_receipt.html',function (err, data){
        if (err) {
            console.log(err);
        } else {
            var renderedHtml = ejs.render(data, {cart: orderInfo.cart, subtotal: orderInfo.subtotal, fee: orderInfo.fee, total: orderInfo.total, deliveryInfo: delivery});

            smtpTransport.sendMail({
                from: "Test <[email protected]>",
                to: orderInfo.user.user.ownerName + " <" + orderInfo.user.user.email +">",
                subject: "Thanks for your order!",
                html: renderedHtml
            }, function(error, response){
                if(error) {
                    console.log(error);
                } else {
                    console.log("Mail sent: " + response.message);
                }
            });
    }
});

I'm open to using a different platform outside ejs as well.

3

There are 3 answers

0
jmalatras On BEST ANSWER

Used EmailTemplates for CrocodileJS with ejs to solve this.

0
shivshankar On

Comment ejs.render use data.replace to replace varible cart , subtotal, fee etc.

0
Lukasz Wiktor On

The error TypeError: this.templateText.replace is not a function error occurs because fs.readFile returns a raw buffer in the callback data. If you pass encoding as a second argument to fs.readFile then the callback data will be a string and ejs won't complain anymore:

fs.readFile('buyer_receipt.html', 'utf-8', function (err, data) {
    // 'utf-8' encoding specified so now data is a string instead of a raw buffer
})