在 JavaScript 和 SendGrid 中格式化电子邮件

Formatting an email in JavaScript and SendGrid

我试图将格式化的字符串传递到我的函数中,但是当发送电子邮件时,文本没有逐行显示,这正是我想要的。

var bodySummary = nominatorName + "\n" + nominatorRegion

                // Run email Cloud code
                Parse.Cloud.run("sendEmail", {
                    toEmail: "test@gmail.com",
                    subject: "Email Test",
                    body: bodySummary
                }).then(function(result) {
                    // make sure to set the email sent flag on the object
                    console.log("result :" + JSON.stringify(result));
                }, function(error) {
                    // error
                });

我正在使用 SendGrid 和 Parse Cloud Code 在我的网络应用程序中生成电子邮件:

Parse.Cloud.define("sendEmail", function(request, response) {

  // Import SendGrid module and call with your SendGrid API Key
  var sg = require('sendgrid')('API_KEY');

  // Create the SendGrid Request
  var reqSG = sg.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: {
      personalizations: [
        {
          to: [
            {
              // This field is the "to" in the email
              email: request.params.toEmail,
            },
          ],
          // This field is the "subject" in the email
          subject: request.params.subject,
        },
      ],
      // This field contains the "from" information
      from: {
        email: 'no-reply@test.com',
        name: 'Test',
      },
      // This contains info about the "reply-to"
      // Note that the "reply-to" may be different than the "from"
      reply_to: {
        email: 'no-reply@test.com',
        name: 'Test',
      },
      content: [
        {
          // You may want to leave this in text/plain,
          // Although some email providers may accept text/html
          type: 'text/plain',
          // This field is the body of the email
          value: request.params.body,
        },
      ],
    },
  });

  // Make a SendGrid API Call
  sg.API(reqSG, function(SGerror, SGresponse) {
    // Testing if some error occurred
    if (SGerror) {
      // Ops, something went wrong
      console.error('Error response received');
      console.error('StatusCode=' + SGresponse.statusCode);
      console.error(JSON.stringify(SGresponse.body));
      response.error('Error = ' + JSON.stringify(SGresponse.body));
    } 
    else {
      // Everything went fine
      console.log('Email sent!');
      response.success('Email sent!');
    }
  });

});

最终结果电子邮件应如下所示:

nominatorName
nominationRegion

目前看起来是这样的:

nominatorName nominatorRegion

可能有两种方法可以完成。

使用HTML正文

  var bodySummary = nominatorName + "<br>" + nominatorRegion

使用换行转义字符

   var bodySummary = nominatorName + "\r\n" + nominatorRegion

您需要将换行符 \n 替换为 HTML 换行符 <br>

例如:

var bodySummary = nominatorName + '<br>' + nominatorRegion;