sendgrid-nodejs: Send bulk mail get error 401 Unauthorized

I’m using @sendgrid/mail module on Google Cloud Functions.

My mails are formatted like this:

{
    to: user.email,
    from: user.fromail,
    cc: user.tl_email,
    subject: 'Test',
    html: setTemplate(),
    attachments: [{
     filename: 'test.png',
     content: test,
     content_id: 'test',
     disposition: 'inline'
   },
   ...]
  };

I have an array of mails with different “to” and different html emails.

When I use sgMail.send(emailsArray) and user.email is just me, then the mails will be sent so the api key is working.

When I use sgMail.send(emailsArray) and user.email are different between them, I get this error:

{ Error: Unauthorized
    at Request.http [as _callback] (node_modules/@sendgrid/client/src/classes/client.js:124:25)
    at Request.self.callback (node_modules/request/request.js:185:22)
    at emitTwo (events.js:126:13)
    at Request.emit (events.js:214:7)
    at Request.<anonymous> (node_modules/request/request.js:1161:10)
    at emitOne (events.js:116:13)
    at Request.emit (events.js:211:7)
    at IncomingMessage.<anonymous> (node_modules/request/request.js:1083:12)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:111:20)
  code: 401,
  message: 'Unauthorized',
  response: 
   { headers: 
      { server: 'nginx',
        date: 'Fri, 16 Aug 2019 08:00:04 GMT',
        'content-type': 'application/json',
        'content-length': '74',
        connection: 'close',
        'access-control-allow-origin': 'https://sendgrid.api-docs.io',
        'access-control-allow-methods': 'POST',
        'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
        'access-control-max-age': '600',
        'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html' },
     body: undefined } }

Any help?

Technical details:

“@sendgrid/mail”: “^6.4.0”, Node.js Version: “^8.0.0”

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 5
  • Comments: 26 (6 by maintainers)

Most upvoted comments

More context: We’ve been using this package for almost two years. February 25 was the first time this ever happened for us. Then March 15 and March 17 and now twice today. This issue isn’t resolved and seems to be getting worse.

@childish-sambino thanks for your response. To provide some more context, my API key is hardcoded (it doesn’t matter in my case). I’ll get this error on the same sendMail call. Specifically, the email will successfully send to some of the recipients, but one or more will not send and get this error instead. It’s always fine in the to field (I only ever have one email here), but the cc field with multiple emails is where the issue arises for me.

I have tried to recreate the error but it never happens. It’s only in a prod environment where I can’t simply resend them because it would result in some annoyed customers.

Changing my previous comment about leaving this open to track handling empty/undefined/null/blank API keys. Let’s use https://github.com/sendgrid/sendgrid-nodejs/issues/1068 to track that work.

I tried multiple changes :

  • using sgMail.send instead of sgMail.sendMultiple
  • adding a small delay of half a second between 2 calls
  • hardocde the API key
const sgMail = require('@sendgrid/mail');
const SENDGRID_MY_TEMPLATE_ID = process.env.SENDGRID_MY_TEMPLATE_ID;
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

sgMail.setApiKey('HARDCODED_API_KEY');

class Mail {
  static async sendReport(recipientEmails, data) {
    const email = {
      to: recipientEmails,
      bcc: ['guy1@xxx.com', 'guy2@xxx.com'],
      from: {
        email: 'hello@mycompany.com',
        name: 'MyCompany',
      },
      replyTo: 'hello@mycompany.com',
      template_id: SENDGRID_MY_TEMPLATE_ID,
      asm: {
        group_id: 1234,
      },
      dynamic_template_data: data,
    };

    try {
      await sgMail.send(email);
      await sleep(500);

    } catch (e) {
      console.log('ERROR Sending Report', e);
      console.log('ERROR Sending Report', e.toString());
      console.log('ERROR Sending Report', e.response.body);
      throw e;
    }
  }
}

But same issue …

What is strange is that the corresponding source code seems clean, so kind of difficult to troubleshoot without the help of SendGrid devs accessing the API code …

Hi,

I have a very similiar issues with the SDK here (Using NodeJS SDK 6.4.0), and customer support sent me here as they think it’s an issue from the SDK itself. I often send emails at the same time, from the same server, but got different answer from the API calls.

Exemple :

  • email sent to user1@xxx.com, with API key YYY ==> email accepted
  • email sent to user2@xxx.com, with API key YYY ==> rejected with error 401, with the same error message than above
  • email sent to user3@xxx.com, with API key YYY ==> email accepted

Here are some figures about one day, when we tried to send multiple email using the SDK to call SendGrid :

  • we tried to send 70 emails (with the same API key)
  • each of this email had 1 email address in “to” field and 2 emails adresses in “bcc” field
  • These API calls were made from 18 differents servers (in fact 18 different Heroku dynos, some of them might be on the same serveur)
  • 52 calls were accepted by the API, and 18 were rejected with “401 Unauthorized Error”
  • In those 18 rejected with 401 error, 7 were rejected with the Error body being “undefined”, and 11 were rejected with Error body being “[ { message: ‘Could not authenticate’, field: null, help: null } ] }”
  • Everything was executed between 06:00:00 AM and 06:00:02 AM
  • The source code using the uses the SDK method sgMail.setApiKey(SENDGRID_API_KEY) to set up the key (which is well set up for each of the calls, I saw that reading the field sgMail.client.apiKey) and we use the SDK method sgMail.sendMultiple(email) to send the emails.

Can there be concurrency issues with the SDK when trying multiple calls with the same API Key ?

Here is the code used :

const sgMail = require('@sendgrid/mail');

const SENDGRID_API_KEY = process.env.SENDGRID_API_KEY;
const SENDGRID_MY_TEMPLATE_ID = process.env.SENDGRID_MY_TEMPLATE_ID;

sgMail.setApiKey(SENDGRID_API_KEY);

class Mail {
  static async sendReport(recipientEmails, data) {
    const email = {
      to: recipientEmails,
      bcc: ['guy1@xxx.com', 'guy2@xxx.com'],
      from: {
        email: 'hello@mycompany.com',
        name: 'MyCompany',
      },
      replyTo: 'hello@mycompany.com',
      template_id: SENDGRID_MY_TEMPLATE_ID,
      asm: {
        group_id: 1234,
      },
      dynamic_template_data: data,
    };

    try {
      await sgMail.sendMultiple(email);
    } catch (e) {
      console.log('ERROR Sending Report', e);
      console.log('ERROR Sending Report', e.toString());
      console.log('ERROR Sending Report', e.response.body);
      throw e;
    }
  }
}

the problem ist not solved yet; I am using latest version 7 and get sometimes:

Unauthorized (401) Error: Unauthorized at ResponseError (node_modules/@sendgrid/helpers/classes/response-error.js:19:5) at axios.then.catch.error (node_modules/@sendgrid/client/src/classes/client.js:105:29) at process._tickCallback (internal/process/next_tick.js:109:7)

code: 401, message: ‘Unauthorized’, response: { headers: { server: ‘nginx’, date: ‘Fri, 24 Apr 2020 12:45:01 GMT’, ‘content-type’: ‘application/json’, ‘content-length’: ‘74’, connection: ‘close’, ‘access-control-allow-origin’: ‘https://sendgrid.api-docs.io’, ‘access-control-allow-methods’: ‘POST’, ‘access-control-allow-headers’: ‘Authorization, Content-Type, On-behalf-of, x-sg-elas-acl’, ‘access-control-max-age’: ‘600’, ‘x-no-cors-reason’: ‘https://sendgrid.com/docs/Classroom/Basics/API/cors.html’ }, body: ‘’ } }

Support says:

Mar 24, 12:33 PM PDT Hi,

Thanks for your reply and additional insight. I checked with our team regarding this issue. As it turns out, making rapid Mail Send calls in a row can intermittently lead to an odd 401 error. I sincerely apologize for any inconvenience caused. In this instance, we recommend implementing some form of retry logic within your code when you receive the 401 error as a workaround.

Hopefully, this information was helpful. Please let me know if I was unable to answer your questions, or if you have any other questions or concerns.

Best, …

When does it get fixed and why the issue ist not open if it is still an issue?

@childish-sambino I’ll open a ticket then, thank you! If I end up resolving it with them I will post back here about it

I got same problem, and I removed sendgrid.env and declare SENDGRID_API_KEY as variable

const sgMail = require('@sendgrid/mail');
const SENDGRID_API_KEY='{api_key};
sgMail.setApiKey(SENDGRID_API_KEY);

I confirm that it’s the same for me. Some request are accepted, but others get 401 unauthorized. But it’s really impossible to understand the reason of the 401, because it’s seems random and it not depends on the code for me.