尝试使用带有Angular和Node的SendGrid

时间:2017-12-19 01:17:45

标签: node.js angular sendgrid sendgrid-api-v3

使用Angular和SendGrid,我正在尝试发送电子邮件。我正确安装了NPM包,但是在实现代码方面遇到了问题。我生成了一个API密钥并将其存储在

目录中
echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

打字稿是:

sgemail(){
  const sgMail = require('@sendgrid/mail'); //ERROR: Cannot find name 'require'.
  sgMail.setApiKey(process.env.SENDGRID_API_KEY); //ERROR: Cannot find name 'process'.
  const msg = {
    to: 'test@example.com',
    from: 'test@example.com',
    subject: 'Sending with SendGrid is Fun',
    text: 'and easy to do anywhere, even with Node.js',
    html: '<strong>and easy to do anywhere, even with Node.js</strong>',
  };
  console.log(msg);
  sgMail.send(msg);
}

我按下按钮即可解雇。

Sendgrid在其网站上没有关于导入软件包的信息,例如您必须使用import { Vibration } from '@ionic-native/vibration';来使用Ionic的振动软件包。

1 个答案:

答案 0 :(得分:2)

您可以尝试使用fetch手动向其Send Mail API发送POST请求。别忘了Authorization Headers。下面是一个相同的未经测试的JavaScript代码段。填写YOUR_API_KEY并将电子邮件更新到您的某封电子邮件。

  var payload = {
    "personalizations": [
      {
        "to": [
          {
            "email": "john@example.com"
          }
        ],
        "subject": "Hello, World!"
      }
    ],
    "from": {
      "email": "from_address@example.com"
    },
    "content": [
      {
        "type": "text/plain",
        "value": "Hello, World!"
      }
    ]
  };
  var myHeaders = new Headers({
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_API_KEY",
  });
  var data = new FormData();
  data.append( "json", JSON.stringify( payload ) );
  fetch("https://api.sendgrid.com/v3/mail/send",
  {
      method: "POST",
      headers: myHeaders,
      body: data
  })
  .then(function(res){ return res.json(); })
  .then(function(data){ console.log( JSON.stringify( data ) ) })