简体   繁体   English

使用 SendGridMessage 将模型值插入动态模板

[英]Interpolate model values into dynamic template using SendGridMessage

I'm building my email for sending with the SendGrid library 's SendGridMessage object.我正在构建我的电子邮件以使用SendGrid 库SendGridMessage对象发送。

I'm defining my values as an anonymous type which I'm injecting with the SendGridMessage's SetTemplateData() method:我将我的值定义为我使用 SendGridMessage 的SetTemplateData()方法注入的匿名类型:

var mail = new SendGridMessage
{
    Attachments = new List<Attachment>(),
    From = new EmailAddress()
    {
        Email = emailConfig.FromAddress,
        Name = $"Redacted on behalf of {booking.Member.Client.Name}"
    },
    TemplateId = EmailConstants.ConfirmationEmailTemplateId,
    Subject = "Redacted"
};

mail.Personalizations = new List<Personalization>() {
    new Personalization() {
        Tos = new List<EmailAddress>() {
            new EmailAddress() {
                Email = memberEmail,
                Name = memberName
            },
        }
    }
};
var data = new
{
    memberName = memberName,
    dateOfAppointment = booking.Date.ToString("dd MMM yy"),
    timeOfAppointment = booking.Date.ToString("HH:mm"),
    questionnaireLink = questionnaireLink
};
mail.SetTemplateData(data);

The email gets sent out perfectly fine, but in the email template, my tags {memberName} , {dateofAppointment} , etc. are not being replaced by the values indicated here.电子邮件发送得非常好,但在电子邮件模板中,我的标签{memberName}{dateofAppointment}等并没有被此处指示的值替换。

I've found handlebars but no C# guide to use them;我找到了车把,但没有使用它们的 C# 指南; I'd assume the data I'm submitting above would work so long as I get the tags right in the template... Am I right?我假设我在上面提交的数据只要我在模板中得到正确的标签就可以工作......我是对的吗?

How do I replace the indicated tags ( {memberName} , {dateofAppointment} , etc.) in my dynamic template with my data values?如何用我的数据值替换动态模板中指定的标签( {memberName}{dateofAppointment}等)?

Make sure your template contains tags using double-brace syntax, like {{memberName}} .确保您的模板包含使用双括号语法的标签,例如{{memberName}} {memberName} (single braces) won't work. {memberName} (单括号)不起作用。

From the SendGrid docs on Handlebars syntax ,Handlebars 语法的 SendGrid 文档中

<!-- Template -->
<p>Hello {{ firstName }}</p>
// Test data
{ "firstName": "Ben" }
<!-- Resulting HTML -->
<p>Hello Ben</p>

If this syntax is used properly in the template, the code in your question will work just fine.如果在模板中正确使用此语法,您问题中的代码将正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM