0

I'm just trying to get a simple example from the SendGrid docs working. This section of code is called from my Node.js + Express application:

function sendConfirmationEmail() {
    const sgMail = require('@sendgrid/mail');
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    const msg = {
        to: 'my@email.com', // Change to your recipient
        from: 'verifiedsender@gmail.com', // Change to your verified sender
        subject: 'Hello, world!',
        text: 'Thank you for your interest. We will let you know if we need any more information.',
        html: '<strong>Thank you for your interest. We will let you know if we need any more information.</strong>',
    };
    sgMail
        .send(msg)
        .then(() => {
            console.log('Email sent')
        })
        .catch((error) => {
            console.error(error)
        });
}

Seeing this logged:

> { Error: Forbidden
    at axios.then.catch.error (node_modules/@sendgrid/client/src/classes/client.js:146:29)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  code: 403,
  message: 'Forbidden',
  response:
   { headers:
      { server: 'nginx',
        date: 'Sat, 27 Feb 2021 15:58:48 GMT',
        'content-type': 'application/json',
        'content-length': '281',
        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: { errors: [Array] } } }

Not sure why this is a CORS error, as it is not happening in the browser. Any ideas?

The suggested workaround from SendGrid is not helpful:

You can create a server-based application, which will protect your API keys from being released to the world. Languages like NodeJS, PHP, Ruby, Python, C#, Go, and Java, and others can be implemented to make calls to the API from the security of a locked down server environment.

Nate Reed
  • 6,761
  • 12
  • 53
  • 67
  • What makes you think this is CORS related? The 403 error tells me you're not authenticating correctly to SendGrid's serivce. Ensure the api key you are using has the needed permissions to send and email – Brettski Feb 27 '21 at 16:49
  • Does this answer your question? [Node JS: Sendgrid Mail 403 'Forbidden' error](https://stackoverflow.com/questions/61149142/node-js-sendgrid-mail-403-forbidden-error) – Brettski Feb 27 '21 at 16:55
  • In the error there is access to the response and in the body there is an array of errors. What do they say? – philnash Mar 01 '21 at 02:56
  • Did you managed to resolve this issue @nate-reed – Bozhinovski Jan 23 '23 at 09:47

0 Answers0