0

I'm trying to send emails from netlify functions with the api from sparkpost. But when I'm testing the function with functions:invoke verify-email --no-identity I get only a 401 error

I have this simple function

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
  });
}

and this is the error message I get. I have already recreated the api-key but with the same result

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.
Gregor Voinov
  • 2,203
  • 7
  • 34
  • 52

1 Answers1

2

There is likely one of two problems going on here.

  1. Make sure your API key has transmission read/write enabled here https://app.sparkpost.com/account/api-keys

  2. You are in the EU and trying to use the US server. In that case, you can do something like this:

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

or

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

See some details here https://github.com/SparkPost/php-sparkpost/issues/180

Yepher
  • 1,465
  • 12
  • 25