1

使用 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 的振动包。

4

1 回答 1

2

您可以尝试使用fetch手动发送 POST 请求到他们的Send Mail API。并且不要忘记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 ) ) })
于 2017-12-20T18:30:05.250 回答