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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With