我正在尝试使用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并不是很好,它主要遍历字段名称并且没有提供示例。感谢您提供的任何帮助!
EDIT
只是为了更新问题,我在前端响应中向自己发送了一个错误,发现与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
对象中的“内容”,并且一切正常。
答案 0 :(得分:2)
根据documentation ... msg
具有错误的元素:
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'test@example.com',
from: 'test@example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg)
.then(() => {
/* assume success */
})
.catch(error => {
/* log friendly error */
console.error(error.toString());
/* extract error message */
const {message, code, response} = error;
/* extract response message */
const {headers, body} = response;
});