node.js - 从 Node.js 中的 sendGrid 发送电子邮件时出现“UnhandledPromiseRejectionWarning:错误:禁止”
问题描述
我正在按照他们网站上的说明将 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.
解决方案
我也面临着类似的问题。我认为他们需要更新文档。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)
})
现在,未处理的 Promise 拒绝错误将消失,并且您将收到错误为什么 Promise 被拒绝。
就像是
发件人地址与已验证的发件人身份不匹配。在解决此错误之前无法发送邮件。访问https://sendgrid.com/docs/for-developers/sending-email/sender-identity/查看发件人身份要求
这是不言自明的。转到指定的链接,它将引导您验证自我身份。完成后,它应该可以正常工作。
链接 https://sendgrid.com/docs/ui/sending-email/sender-verification/
推荐阅读
- python - 如何以pythonic方式查看for循环中的for循环
- javascript - 一个反应应用程序导入另一个反应应用程序?
- python - 将 pytds 与 sqlalchemy 一起使用
- python - 如何在使用颜色图作为图例的同时创建多个 matplotlib 图?
- corda - 如何为 Corda 设置 H2
- filter - 在地图视图中过滤特征 React-Map-gl React Hooks
- javascript - 具有相似日期的相同时刻语法给出完全不同的结果
- php - 我正在尝试显示文件夹中的多个随机非重复图像,但我得到空白图像
- python - >比较中的ValueError
- python - 使用 Python 绘制已经计算好的混淆矩阵