我从 Sendgrid 网站设计了一个模板。我们称之为 sendgrid.html
我正在尝试使用 sendgrid.html
的设计从 Nodejs
发送电子邮件。下面是我的 Nodejs 代码:
function sendVoucherCodeEmail (emailAddress, voucherCode){
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: emailAddress,
from: 'example@example.com',
subject: 'YourCode',
text: ''
};
}
我想将 emailAddress
和 voucherCode
传递到 html 内容中,并将其作为电子邮件发送给用户。我该怎么做 ?先感谢您。
最佳答案
最好在sendgrid上创建一个模板,并在使用sendgrid API发送时只输入模板的ID。通过这样做,您可以轻松更改内容,而无需部署新的应用程序。您仍然可以将所需的数据注入(inject)到模板中。
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
sgMail.setSubstitutionWrappers('{{', '}}');
const msg = {
to: emailAddress,
from: 'example@example.com',
templateId: templateId,
dynamic_template_data: {emailAddress, voucherCode},
};
!注意:sendgrid 更改其 API。因此,V2 中的 substitutions
被 V3 中的 dynamic_template_data
替换:https://github.com/sendgrid/sendgrid-nodejs/issues/703
要了解如何创建模板,可以访问官方文档:https://sendgrid.com/docs/User_Guide/Transactional_Templates/create_and_edit_transactional_templates.html
模板中的占位符应被 {{
}}
包围。例如:{{emailAddress}}
关于node.js - 如何从 Nodejs 发送包含 html 内容的 SENDGRID 电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51841206/