【发布时间】:2018-12-16 21:11:51
【问题描述】:
我正在尝试在我的 Google Cloud Function 中使用 SendGrid 发送电子邮件。我在 Firebase 环境变量中有我的密钥,所以它存在。
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);
这是我的 GCF .ts 代码:
代码
const msg = {
to: to,
from: from,
subject: 'Email Subject',
content: [{
type: "text/html",
value: body
}]
};
await sgMail.send(msg)
.then(r => {
console.log(r);
});
当我触发该函数并检查我的日志时,这是我得到的错误:
错误
error: { Error: Bad Request
at ResponseError (node_modules/@sendgrid/mail/node_modules/@sendgrid/helpers/classes/response-error.js:19:5)
at Request.http [as _callback] (node_modules/@sendgrid/mail/node_modules/@sendgrid/client/src/classes/client.js:124:25)
at Request.self.callback (node_modules/@sendgrid/mail/node_modules/request/request.js:185:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (node_modules/@sendgrid/mail/node_modules/request/request.js:1161:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (node_modules/@sendgrid/mail/node_modules/request/request.js:1083:12)
at IncomingMessage.g (events.js:292:16)
code: 400,
message: 'Bad Request',
response:
{ headers:
{ server: 'nginx',
date: 'Sun, 16 Dec 2018 16:27:56 GMT',
'content-type': 'application/json',
'content-length': '402',
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: [Object] } } }
有没有人熟悉这个错误?它提到了 CORS,但这没有任何意义,因为它是云功能,而不是浏览器。 SendGrid API 不是那么好,它主要遍历字段名称并且没有提供示例。感谢您提供的任何帮助!
编辑
只是为了更新问题,在我发送给自己的前端响应中,我发现与 GCF 日志中的 console.log(error) 不同的错误:
"Email failed: Bad Request (400)
The from object must be provided for every email send.
It is an object that requires the email parameter,
but may also contain a name
parameter. e.g. {"email" : "example@example.com"} or
{"email" : "example@example.com", "name" : "Example Recipient"}.
from.email
http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.from"
编辑 2:解决方案
我的电子邮件来源来自 Firestore 中的一个文档,我试图获取一个不存在的字段,因为我查询了错误的文档,因此 from 是 undefined。更正了它,并根据下面的建议/答案删除了 msg 对象中的“内容”,一切正常。
【问题讨论】:
标签: node.js firebase google-cloud-functions sendgrid