首页 > 解决方案 > 如何使用 Javascript 格式化电子邮件中的 HTML?

问题描述

我有一个发送电子邮件的 javascript 函数(服务器端)我希望将电子邮件的正文以 HTML 格式显示,使其看起来比文本更好。

这是创建电子邮件的代码

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);
};

当我得到它时,它看起来像这样:

-----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>

这是我的“发送”功能中的代码

  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 定义如下:

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,
  },
});

标签: javascripthtmlemail

解决方案


好的..所以事实证明这是一个发送 HTML 或文本的 nodemailer 选项:

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

推荐阅读