Search code examples
htmlnode.jsnodemailer

Is there a way to send an HTML template through nodemailer to appear in the mail?


I'm trying to organize a template for the mail I'm trying to send to my email using MERN stack and nodemailer. This is kind of what I want to send as the response:

const {name, email, phone, message} = req.body;

    const mailOptions = {
        from: process.env.AUTH_EMAIL,
        to: 'vs61@queensu.ca',
        subject: 'Community Partnership Project Contact Form Inquiry',
        html: <div>Name: {name}<br/>Email: {email}<br/>Phone: {phone}<br/>Message: {message}</div>
    }

Except for the fact that this doesn't work. The backend crashes when I do it, this is the crash log:

      html: <div>Name: {name}<br/>Email: {email}<br/>Phone: {phone}<br/>Message: {message}</div>
              ^

SyntaxError: Unexpected token '<'
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47
[nodemon] app crashed - waiting for file changes before starting...

I'm not sure how to send html code, is there a way to do this?


Solution

  • Yes, you can set the email template in nodemailer but your syntax is wrong.

    const name ='abc',email='abc@yopmail.com',phone='1234',message='hello there'
        const mailOptions = {
            from: process.env.AUTH_EMAIL,
            to: 'vs61@queensu.ca',
            subject: 'Community Partnership Project Contact Form Inquiry',
            html: `<div><p>Name: ${name}</p><br/><p>Email: ${email}</p><br/><p>Phone: ${phone}</p><br/><p>Message: ${message}</p></div>`
        }
    

    Note:'You forgot to add template literal and ${} so you can add dynamic values.'