Search code examples
javascripthtmlnodemailer

Extra orphaned character in email from nodemailer template email


I'm using "nodemailer": "^6.5.0" to send emails using a HTML template. Everything is working fine except for when I map an array field, I get an extra , character after each item and I can't work out where it's comming from.

extra characters

This is the HTML element from the rendered email copied straight from the Chrome inspector in Gmail:

<div>
  <p><b>Brad Stewart 11-03-21 15:26:</b> Another note...</p>
  ,
  <p><b>Brad Stewart 11-03-21 15:44:</b> And another note ...</p>
  ,
  <p><b>Brad Stewart 14-03-21 13:07:</b> test again</p>
  ,
  <p><b>Brad Stewart 14-03-21 13:15:</b> And testing again...</p>
</div>

This is the section of the HTML template

`<p>
  <b>Notes:</b>
  <div>
    ${task.notes
        ? task.notes.map(
            (note) =>
              `<p><b>- ${note.created_by_name} ${moment(note.date)
                .tz('Australia/Perth')
                .format('DD-MM-YY HH:mm')}:</b> ${note.note}</p>`
          )
        : '-'
    }
  </div>
</p>`

Thanks for any help or ideas to remove these orphaned characters.


Solution

  • The array is converted to a string by calling Array.prototype.toString since it's inside template literals. The toString method returns the array elements joined by commas as a string.

    From the docs,

    JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.

    const arr = ['Note 1', 'Note 2', 'Note 3']
    console.log(`Notes: ${arr}`)
    console.log(arr.toString())

    You can use Array.prototype.join to explicitly convert it to a string.

    task.notes
      .map(
        (note) =>
          `<p><b>- ${note.created_by_name} ${moment(note.date)
            .tz('Australia/Perth')
            .format('DD-MM-YY HH:mm')}:</b> ${note.note}</p>`
      )
      .join('')