Waleed Shahzaib
Waleed Shahzaib

Reputation: 1706

HTML email body not rendering variables in template literals

I am using nodemailer for sending email. I want to display some data in email body which is received from client side. In email body that data is treated as string and its value is not printing.

code is:

let mailOptions = {
                from: '[email protected]', // sender addressl
                to: '[email protected]', // list of receivers
                cc: '',            
                subject: 'Hello ✔', // Subject line
                // text: 'Hello world?', // plain text body                
                html: `<b>Hello World?</b>
                    <h3>data.resourceName</h3>
                `
            };

data is an object which contains multiple fields, but when I print e.g. data.resourceName it prints it as it is not its value. Its treating it a string. Whether I need to change its mimetype or something else? Please tell how to solve this issue. Thanks

Upvotes: 0

Views: 1380

Answers (3)

Gorav Singal
Gorav Singal

Reputation: 538

In addition to above answers, I think you do not want to use templates. Although, you should think of using templating libraries like handlebars, Mustache etc.

If not, below is what you want to do:

let mailOptions = {
                from: '[email protected]', // sender addressl
                to: '[email protected]', // list of receivers
                cc: '',            
                subject: 'Hello ✔', // Subject line
                // text: 'Hello world?', // plain text body                
                html: `<b>Hello World?</b><br><h3>' + data.resourceName + '</h3>`
            };

Upvotes: 0

rockchalkwushock
rockchalkwushock

Reputation: 1273

I agree with the above answer that you are missing the template literal syntax and that is probably your issue. I pass my data from the client to a template for the email which is just one big template literal and destructure the data properties inside of the template.

Mail Client

Email as template literal

Upvotes: 1

mbrandau
mbrandau

Reputation: 554

Since you're using template literals, you need to wrap data.resourceName like this: ${data.resourceName}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Upvotes: 2

Related Questions