从Node.js中的sendGrid发送电子邮件时出现“ UnhandledPromiseRejectionWarning:错误:禁止”

时间:2020-04-12 12:12:34

标签: node.js visual-studio-code sendgrid

按照他们网站上的说明,我将sendgrid与以下代码集成到我的node.js项目中

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

const sendGridAPIKey = "API key"

sgMail.setApiKey(sendGridAPIKey)

const msg = {
 to: 'agrawalanuj751997@gmail.com',
 from: 'agrawalanuj751997@gmail.com',
 subject:'My first mail from node',
 text:"I'm sending myself an email"
}

sgMail.send(msg)

我的日志中出现以下错误。我从多个帐户尝试了多个API密钥,但仍然遇到相同的错误。

(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.

3 个答案:

答案 0 :(得分:16)

我也面临着类似的问题。我认为他们需要更新文档。 send方法返回一个您尚未处理的承诺,这就是您收到错误的原因。

更改

sgMail.send(msg)

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

现在,未处理的诺言拒绝错误将消失,并且您将得到为什么诺言被拒绝的错误。

类似

发件人地址与验证的发件人身份不匹配。解决此错误之前,无法发送邮件。访问https://sendgrid.com/docs/for-developers/sending-email/sender-identity/以查看发件人身份要求

这很不言自明。转到指定的链接,它将引导您验证自己的身份。完成后,它应该可以正常工作。


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

答案 1 :(得分:0)

我也遇到了类似的问题。 send 方法返回一个您尚未处理的承诺,这就是您收到错误的原因。

sgMail.send({  
    to: 'arjunregmi148@gmail.com',
    from: 'arjunregmi148@gmail.com',
    subject: 'This is my first creation',
    text:'Be safe from corona virus'
}).then(() => {
    console.log('Message sent')
}).catch((error) => {
    console.log(error.response.body)
})

答案 2 :(得分:-2)

您无法验证用户在sendgrid上验证单个发件人