Sendgrid-nodejs: The provided authorization grant is invalid, expired, or revoked (401)

Created on 1 Sep 2016  ·  15Comments  ·  Source: sendgrid/sendgrid-nodejs

Issue Summary

When sending an email using the Nodejs V3 API, I receive the following error message:

{ 
    [SendGridError: Response error] message: 'Response error' } 
    { 
        statusCode: 401, 
        body: '{"errors":[{"message":"The provided authorization grant is invalid, expired, or revoked","field":null,"help":null}]}', 
        headers: { 
            server: 'nginx', 
            date: 'Wed, 31 Aug 2016 18:34:49 GMT', 
            'content-type': 'application/json', 
            'content-length': '116', 
            connection: 'close', 
            'x-frame-options': 'DENY'
        } 
    }
}

This message is produced on a localhost instance as in a live server environment.

Code snippet

The following code is used to send the email:

var helper = require('sendgrid').mail,
sg = require('sendgrid')(SENDGRID_API_KEY);

var from_email = new helper.Email('[email protected]');
var to_email = new helper.Email(myOwnEmail);
var subject = 'Subject';
var content = new helper.Content('text/plain', 'test');
var mail = new helper.Mail(from_email, subject, to_email, content);

var request = sg.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: mail.toJSON()
});

sg.API(request, function(err, response) {
    console.log(err, response);
    if (!err) {
        res.send({
            message: 'An email has been sent to the provided email with further instructions.'
        });
    } else {
        return res.status(400).send({
            message: 'Failure sending email'
        });
    }
});

Technical details:

  • localhost: Windows 10 x64
  • liveserver: Heroku
  • sendgrid-nodejs Version: 4.0.2
  • npm version: 3.7.5
  • node version: 4.4.5
help wanted question

Most helpful comment

I created a new account with a new API KEY with the exact same code. Now I'm able to send emails while waiting for support takes forever.

All 15 comments

Hi @ninox92,

This means there is an issue with your API Key.

First, please verify the value of SENGRID_API_KEY

Then please contact our support team at https://support.sendgrid.com so they can dig into what is wrong with your API Key's permissions.

Thanks!

SENGRID_API_KEY has been verified and tried a newly created API key but also reproduced the same error message.

Using a CURL POST request to send an email I though was able to successfully send an email using the same API key.

I'll try to contact support once again.

In the code you posted, you have SENGRID_API_KEY and I'm thinking you meant SENDGRID_API_KEY

Thank you for pointing out the variable name typo. I'll change that. Nevertheless the variable was correctly filled with my API key.

I just tried again and I could not reproduce. Here is the code I used:

var helper = require('sendgrid').mail;
var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);

var from_email = new helper.Email('[email protected]');
var to_email = new helper.Email('[email protected]');
var subject = 'Subject';
var content = new helper.Content('text/plain', 'test');
var mail = new helper.Mail(from_email, subject, to_email, content);

var request = sg.emptyRequest({
  method: 'POST',
  path: '/v3/mail/send',
  body: mail.toJSON(),
});

sg.API(request, function(err, response) {
  console.log(response.statusCode);
  console.log(response.body);
  console.log(response.headers);
});

Could you also provide the cURL request that is working for you?

I used the following Hello, World! example from the Sendgrid curl examples page

curl --request POST \
  --url https://api.sendgrid.com/v3/mail/send \
  --header 'Authorization: Bearer SENDGRID_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{"personalizations": [{"to": [{"email": "<my-own-email>"}]}],"from": {"email": "[email protected]"},"subject": "Hello, World!","content": [{"type": "text/plain", "value": "Heya!"}]}'

Hello @ninox92,

Have you tried using the code sample I provided?

That error means that your API Key is not getting set properly.

If you are not using environment variables, you would have:

var sg = require('sendgrid')('SG.XXXXXXXXXXXXXXXXXXX');

I created a new account with a new API KEY with the exact same code. Now I'm able to send emails while waiting for support takes forever.

Thanks for following up, I'm glad you are up and running! Please let us know if you run into any other issues.

thank you it help me a lot

hi guys i'm having a trouble it gave me the same error here's the code i use.

const express = require('express');
const app = express();

var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);

var port = process.env.PORT || 8080;

app.get('/', function (req, res){

var helper = require('sendgrid').mail;
var fromEmail = new helper.Email('[email protected]');
var toEmail = new helper.Email('[email protected]');
var subject = 'Hello World from the SendGrid Node.js Library!';
var content = new helper.Content('text/plain', 'Hello, Email!');
var mail = new helper.Mail(fromEmail, subject, toEmail, content);

var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON()
});

sg.API(request, function (error, response) {
if (error) {
console.log('Error response received');
}
console.log(response.statusCode);
console.log(response.body);
console.log(response.headers);
});

});

app.listen(port,function(){
console.log("Listening to:* " + port);
});

and on my .env.example file
SENDGRID_API_KEY=code here /* i do have the API code here */

if you need to send email via api with post methode you should do like this:

var helper= require('sendgrid').mail;

router.post('/' , function ( req , res) {

var sg=require('sendgrid')('your api key from your account');
var formEmail= new helper.Email('[email protected]');
var toEmail= new helper.Email(req.body.mail);
var subject='text';
var content = new helper.Content('text/plain', 'Your password has been successfully changed');

var mail = new helper.Mail(formEmail, subject, toEmail, content);

var request =sg.emptyRequest({
    method:'POST',
    path: '/v3/mail/send',
    body: mail.toJSON()
});

sg.API(request , function (error , response) {
    if(error){

        console.log('Error response not valid');

    }
});

})

module.exports=router;

Sorry for the trouble its working now i thought it was an error it was a 202 error . Sorry

Just for anyone having the same issue I did. If you are using one of SendGrid's client libraries make sure it is up to date!

I was using the C# library version 9.9.0 and started getting this error out of the blue. I updated to version 9.10.0 and it resolved the issue.

Interestingly I had exactly the same issue with the C# Twilio library that an update resolved without me having to change any code. Just a conincidence with Twilio aquiring SendGrid?

In my case was the next:

My IDE(Intellij CE 2020.10.3) wasnt recognizing my enviromet variable correctly, instead of getting my sendgrid api key value ej: SG.sddDDeq.qwt it was taking the path to the .env file, ej: "C:/Users/Me/MyProjectRootFolder/sendgrid.env" and providing it to the Sendgrid request Headers as "Authorization": "Bearer C:/Users/Me/MyProjectRootFolder/sendgrid.env:" wich is the problem that leads to the error "The provided authorization grant is invalid...".

Soo... try to debug you request headers and verify the provided key is valid(you ide recognize your env variable),and you also need to add a Domain Authentication or Single Sender Verification from you SendGrid Dashboard .

Hope this help somebody.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mikemaccana picture mikemaccana  ·  4Comments

kiranshashiny picture kiranshashiny  ·  4Comments

wooyah picture wooyah  ·  4Comments

danielflippance picture danielflippance  ·  4Comments

prasoonjalan picture prasoonjalan  ·  3Comments