MLissCetrus
MLissCetrus

Reputation: 473

How can I use Javascript to format HTML in an email?

I have a javascript function (server side) that sends an email I would like to have the body of the email in HTML to make it look a little nicer than just text.

Here is the code that creates the email

sendTestEmail = (to) => {

  var subject = 'Email Test';
  var body = '';
  body = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">';
  body += '<html>';
  body += '<head>';
  body += '<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">';
  body += '</head>';
  body += '<body bgcolor="#ffffff" text="#000000">';
  body += 'This should be body text <br>';
  body += 'More body text <br>';
  body += 'Even more body text<br>';
  body += '<br>';
  body += 'something that needs white space separation <br>';
  body += '<br>';
  body += '<br>';
  body += '<div class="moz-signature"><i><br>';
  body += 'signature<br>';
  body += '</i></div>';
  body += '</body>';
  body += '</html>';

  return send(to, subject, body);
};

it looks like this when I get it:

-----Original Message-----
From: (removed) 
Sent: Monday, November 9, 2020 9:31 AM
To: (removed)
Subject: Email Test

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"></head><body bgcolor="#ffffff" text="#000000">This should be body text <br>Even more body text<br><br>something that needs white space separation<br><br><br><div class="moz-signature"><i><br>signature<br></i></div></body></html>

Here is the code in my 'send' function

  var mailOptions = {
    from: from,
    to: to,
    subject: subject,
    text: body,
  };

  transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
      errors.message = error.message;
      console.log(msgPrefix, 'ERROR', JSON.stringify(errors));
      return errors;
    } else {
      errors.code = 200;
      errors.data = info.response;
      console.log(msgPrefix, 'Response', info.response);
      return errors;
    }
  });

transporter is defined like this:

const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
  host: email_host,
  secureConnection: email_secureConnection,
  requireTLS: email_requireTLS,
  port: email_port,
  tls: {
    ciphers: email_cipher,
  },
  auth: {
    user: email_user,
    pass: email_password,
  },
});

Upvotes: 0

Views: 257

Answers (1)

MLissCetrus
MLissCetrus

Reputation: 473

OK.. so it turns out it is a nodemailer option to send HTML or text:

  var mailOptions = {
    from: from,
    to: to,
    subject: subject,
    text: body,
    html: body, // this fixes it !
  };

Upvotes: 1

Related Questions