使用 api 发送邮件时 sparkpost 出现授权错误

Authorisation error with sparkpost when sending mails with their api

我正在尝试使用来自 sparkpost 的 api 从 netlify 函数发送电子邮件。但是当我使用 functions:invoke verify-email --no-identity 测试函数时,我只收到 401 错误

我有这个简单的功能

const SparkPost = require('sparkpost')
const client = new SparkPost(process.env.SPARKPOST)
const key = process.env.SPARKPOST
const handler = async(event, context, callback) => {
  console.log(key) //outputs the key, so this is not the problem
  return client.transmissions.send({
    options: {
      sandbox: true
    },
    content: {
      from: 'testing@sparkpostbox.com',
      subject: 'Hello, World!',
      html:'<html><body><p>Testing SparkPost - the world\'s most awesomest email service!</p></body></html>'
    },
    recipients: [
      {address: 'email@gmail.com'}
    ]
  })
  .then(data => {
    console.log('Woohoo! You just sent your first mailing!');
    console.log(data);
    return data
  })
  .catch(err => {
    console.log('Whoops! Something went wrong');
    console.log(err);
    return err
  });
}

这是我收到的错误消息。我已经重新创建了 api-key 但结果相同

Request from ::1: GET /.netlify/functions/verify-email
Whoops! Something went wrong
Error [SparkPostError]: Unauthorized
    at createSparkPostError (/Users/gregorvoinov/Desktop/local work/_intern/icons-manager/node_modules/sparkpost/lib/sparkpost.js:38:15)
    at Request._callback (/Users/gregorvoinov/Desktop/local work/_intern/icons-manager/node_modules/sparkpost/lib/sparkpost.js:128:15)
    at Request.self.callback (/Users/gregorvoinov/Desktop/local work/_intern/icons-manager/node_modules/request/request.js:185:22)
    at Request.emit (events.js:196:13)
    at Request.<anonymous> (/Users/gregorvoinov/Desktop/local work/_intern/icons-manager/node_modules/request/request.js:1154:10)
    at Request.emit (events.js:196:13)
    at IncomingMessage.<anonymous> (/Users/gregorvoinov/Desktop/local work/_intern/icons-manager/node_modules/request/request.js:1076:12)
    at Object.onceWrapper (events.js:284:20)
    at IncomingMessage.emit (events.js:201:15)
    at endReadableNT (_stream_readable.js:1130:12) {
  name: 'SparkPostError',
  errors: [ { message: 'Unauthorized.' } ],
  statusCode: 401
}
Response with status 401 in 850 ms.

这里可能存在两个问题之一。

  1. 确保您的 API 密钥已在此处启用传输 read/write https://app.sparkpost.com/account/api-keys

  2. 您在欧盟并尝试使用美国服务器。在这种情况下,您可以这样做:

'host' => 'api.eu.sparkpost.com',

$httpClient = new GuzzleAdapter(new Client()); $sparky = new SparkPost($httpClient, ['key'=>'**********', 'host' => 'api.eu.sparkpost.com']);

在此处查看一些详细信息https://github.com/SparkPost/php-sparkpost/issues/180