【发布时间】:2017-04-06 04:59:28
【问题描述】:
如何使用 Nodejs 模板化 SendGrid 的内容?
我正在尝试使用 SendGrid 从应用程序中的联系表单发送电子邮件。我有一个通过 HTTP 帖子调用的 Google Cloud 函数。我能够将表单数据作为 JSON 对象传递给我的 Google Cloud 函数,并在我的电子邮件内容中显示一个原始 JSON 对象,但是当我尝试对我的 SendGrid 内容进行模板化时,JSON 对象的属性一直返回为未定义。如何在我的 SendGrid 电子邮件内容中显示不同的 formData 属性?
代码如下:
const functions = require('firebase-functions');
const sg = require('sendgrid')(
process.env.SENDGRID_API_KEY || '<my-api-key-placed-here>'
);
exports.contactMail = functions.https.onRequest((req, res) => {
contactMail(req.body);
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.send("Mail Successfully Sent!");
})
function contactMail(formData) {
const mailRequest = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: {
personalizations: [{
to: [{ email: 'my.email@gmail.com' }],
subject: 'Contact Us Form Submitted'
}],
from: { email: 'noreply@email-app.firebaseapp.com' },
content: [{
type: 'text/plain',
value: `
You have received a contact us form submission. Here is the data:
Name: ${formData.userFirstName} ${formData.userLastName}
Email: ${formData.userEmail}
Subject: ${formData.formSubject}
Message: ${formData.formMessage}
`
}]
}
});
sg.API(mailRequest, function (error, response) {
if (error) {
console.log('Mail not sent; see error message below.');
} else {
console.log('Mail sent successfully!');
}
console.log(response);
});
}
这显示每个模板表达式的未定义。
但是,如果我的内容部分设置为:
content: [{
type: 'text/plain',
value: formData
}]
然后电子邮件内容显示为原始 JSON 对象。
如何清理我的 SendGrid 电子邮件内容并以格式化、更简洁的方式显示我的 JSON 数据?
【问题讨论】:
标签: javascript json node.js ecmascript-6 sendgrid