简体   繁体   中英

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: 'me.waleed28@gmail.com', // sender addressl
                to: 'waleed.shahzaib@nxb.com.pk', // 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 eg 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

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

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

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: 'me.waleed28@gmail.com', // sender addressl
                to: 'waleed.shahzaib@nxb.com.pk', // list of receivers
                cc: '',            
                subject: 'Hello ✔', // Subject line
                // text: 'Hello world?', // plain text body                
                html: `<b>Hello World?</b><br><h3>' + data.resourceName + '</h3>`
            };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM