【问题标题】:Sendgrid sending html email without embedded codeSendgrid 发送没有嵌入代码的 html 电子邮件
【发布时间】:2016-12-07 20:57:37
【问题描述】:

我只想直接输入 ./blabla.html 发送我的 html 文件,而不是创建广告系列或模板。有没有办法在不放置嵌入式代码的情况下发送邮件?如果是这样,我会很高兴,谢谢! 我当前的代码如下所示:

var helper = require('sendgrid').mail
  from_email = new helper.Email("blabla@hotmail.com")
  to_email = new helper.Email("heyhey@gmail.com")
  subject = "Merhaba !"
  content = new helper.Content("text/plain", "selam")
  mail = new helper.Mail(from_email, subject, to_email, content)
}

var sg = require('sendgrid').SendGrid("mysecretapikey")
  var requestBody = mail.toJSON()
  var request = sg.emptyRequest()
  request.method = 'POST'
  request.path = '/v3/mail/send'
  request.body = requestBody
  sg.API(request, function (response) {
    console.log(response.statusCode)
    console.log(response.body)
    console.log(response.headers)
  })

【问题讨论】:

  • 为什么不把 HTML 文件读成这样的字符串:stackoverflow.com/questions/18386361/read-a-file-in-node-js?另请注意,如果要将其作为 HTML 发送,则需要 text/html 替换 content
  • 没关系,但是我找不到该读取操作的放置位置。当我调用 read func 时,它只是读取 cmd 上的内容并将邮件发送给写入函数名称的接收者。有什么帮助吗? @Sebastian-LaurenţiuPlesciuc

标签: html node.js api email sendgrid


【解决方案1】:

您可能需要更新您的 sendgrid 软件包。基于您的要求的工作示例如下所示:

var fs = require('fs');
var path = require('path');

var filePath = path.join(__dirname, 'myfile.html');

fs.readFile(filePath, {encoding: 'utf-8'}, function(err, data) {
    if ( ! err ) {
      var helper = require('sendgrid').mail;
      from_email = new helper.Email("blabla@hotmail.com");
      to_email = new helper.Email("heyhey@gmail.com");
      subject = "Merhaba !";
      content = new helper.Content("text/html", data);
      mail = new helper.Mail(from_email, subject, to_email, content);

      var sg = require('sendgrid')('your api key');
      var requestBody = mail.toJSON();
      var request = sg.emptyRequest();
      request.method = 'POST';
      request.path = '/v3/mail/send';
      request.body = requestBody;
      sg.API(request, function (error, response) {
        if ( ! error ) {
          console.log(response.statusCode);
          console.log(response.body);
          console.log(response.headers);
        } else {
          console.log(error);
        }
      });
    } else {
        console.log(err);
    }
});

myfile.html 文件就在这个 .js 文件旁边,看起来像这样:

<html>
<head>
    <title> Test </title>
</head>
<body>
    <h2> Hi! </h2>
    <p> This is a test email </p>
</body>
</html>

【讨论】:

  • 谢谢!多亏了你,这个真的工作了数千!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-26
  • 2016-11-23
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多