我正在尝试使用sendGrid通过节点发送交易电子邮件。下面是我的代码示例。
const subject = 'Email subject';
const templateId = 'templateId';
const sg = require('sendgrid')(secret);
const request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: {
"personalizations": [
{
"bcc": userEmails,
"substitutions": {
"-userName-": userDetails.name,
"-productPrice-": productDetails.price,
"-productUrl-": productDetails.url,
"-productPercentageDrop-": productDetails.percentageDrop,
"-productName-": productDetails.name,
"-productOriginalPrice-": productDetails.origPrice,
"-productDroppedPrice-": productDetails.dropPrice,
"-productImageUrl-": productDetails.imageUrl
},
"subject": subject.substring(0, 75)
}
],
"from": {
"email": "myemail",
"name": "myname"
},
"content": [
{
"type": "text/html"
}
],
"template_id": templateId
}
});
sg.API(request, function (error, response) {
if (error) {
console.log('Error response received');
}
console.log(response.body.errors);
});
但是每次运行代码时都会收到以下错误消息。
400
message: 'Bad Request', field: null, help: null
在试图找出错误的原因时,这并不是很有帮助。
正在发送正文JSON:
{
"host":"",
"method":"POST",
"path":"/v3/mail/send",
"headers":{
},
"body":{
"personalizations":[
{
"bcc":[
{
"email":"name1@hotmail.com",
"name":"name1"
},
{
"email":"name2@hotmail.com",
"name":"name2"
}
],
"substitutions":{
"-productPrice-":189.5,
"-productUrl-":"http://www.tesco.com/direct/humax-fvp-4000t500-m-smart-freeview-play-hd-digital-tv-recorder-with-wi-fi-500gb/483-1785.prd",
"-productName-":"Tesco direct: Humax FVP-4000T/500 (M) Smart Freeview Play HD Digital TV Recorder with Wi-Fi - 500GB"
},
"subject":"Product Tesco direct: Humax FVP-4000T/500 (M) Smart Freeview Play HD Digita"
}
],
"from":{
"email":"email@pricetracker.io",
"name":"Pricetracker"
},
"content":[
{
"type":"text/html"
}
],
"template_id":"XXXXXX"
},
"queryParams":{
},
"test":false,
"port":""
}
答案 0 :(得分:0)
不知道这对你是否仍然有用,但在使用Sendgrid替换时我遇到了类似的问题。我正在使用sendgrid-php库,但在内部它发送相同的格式。我发现所有替换值都应转换为字符串。例如,productPrice的值应该是这样的:
"-productPrice-": "189.5",
带引号。在我的情况下,我有整数,当我将它们转换为字符串时,一切正常。
答案 1 :(得分:0)
如果你没有将字符串值传递给模板文件,那么 SendGrid 会给你
{"errors":[{"message":"Bad Request","field":null,"help":null}]}
在发送到模板文件之前将所有非字符串值转换为字符串。