【问题标题】:Trying to use SendGrid with Angular and Node尝试将 SendGrid 与 Angular 和 Node 一起使用
【发布时间】:2017-12-19 01:17:44
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    您可以尝试使用fetch 手动向他们的Send Mail API 发送 POST 请求。不要忘记Authorization Headers。下面是一个相同的未经测试的 JavaScript 代码 sn-p 来尝试。填写 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 ) ) })
    

    【讨论】:

    • 访问从源 'localhost:8100' 获取在 'api.sendgrid.com/v3/mail/send' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:'Access-Control-Allow -Origin 标头的值 'sendgrid.api-docs.io' 不等于提供的原点。让服务器发送带有有效值的标头,或者,如果不透明的响应满足您的需要,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
    猜你喜欢
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 2011-12-25
    • 2012-11-22
    • 2023-03-10
    • 2020-10-10
    • 1970-01-01
    相关资源
    最近更新 更多