Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"UnhandledPromiseRejectionWarning: Error: Forbidden" while sending email from sendGrid in Node.js

I'm integrating sendgrid in my node.js project with the following code as per instructions on their website

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

const sendGridAPIKey = "API key"

sgMail.setApiKey(sendGridAPIKey)

const msg = {
 to: '[email protected]',
 from: '[email protected]',
 subject:'My first mail from node',
 text:"I'm sending myself an email"
}

sgMail.send(msg)

I'm getting the following error in my log. I've tried multiple API keys from multiple accounts but still, I'm getting the same error.

(node:16043) UnhandledPromiseRejectionWarning: Error: Forbidden
at Request._callback (node_modules/@sendgrid/client/src/classes/client.js:124:25)
at Request.self.callback (node_modules/request/request.js:185:22)
at Request.emit (events.js:200:13)
at Request.<anonymous> (node_modules/request/request.js:1154:10)
at Request.emit (events.js:200:13)
at IncomingMessage.<anonymous> (node_modules/request/request.js:1076:12)
at Object.onceWrapper (events.js:288:20)
at IncomingMessage.emit (events.js:205:15)
at endReadableNT (_stream_readable.js:1154:12)
at processTicksAndRejections (internal/process/task_queues.js:84:9)
(node:16043) UnhandledPromiseRejectionWarning: Unhandled promise 
rejection. This error originated either by throwing inside of an async 
function without a catch block, or by rejecting a promise which was 
not handled with .catch(). (rejection id: 1)
(node:16043) [DEP0018] DeprecationWarning: Unhandled promise 
rejections are deprecated. In the future, promise rejections that are 
not handled will terminate the Node.js process with a non-zero exit 
code.
like image 483
Anuj Agrawal Avatar asked Apr 12 '20 12:04

Anuj Agrawal


Video Answer


1 Answers

I was also facing the similar issue. I think they need to update the docs. The send method returns a promise that you have not handled that's why you're getting the error.

change

sgMail.send(msg)

to

sgMail.send(msg).then(() => {
    console.log('Message sent')
}).catch((error) => {
    console.log(error.response.body)
    // console.log(error.response.body.errors[0].message)
})

Now, the unhandled promise rejection error will be gone, And you'll get the error why the promise was being rejected.

Something like

The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity requirements

It's pretty self-explanatory. Go to the specified link, and it'll guide you to verify the self identity. Once you complete that, It should work fine.


Links https://sendgrid.com/docs/ui/sending-email/sender-verification/

like image 147
Aniket Kariya Avatar answered Oct 11 '22 13:10

Aniket Kariya