【问题标题】:How to substitute Sendgrid template variables? (in C#)如何替换 Sendgrid 模板变量? (在 C# 中)
【发布时间】:2025-12-09 08:50:01
【问题描述】:

我在我的 SendGrid 模板中定义了一个变量 <%datetime%>。我决定按照这个命名约定遵循已经放置的主题行的<%subject%>。我在示例中看到了不同的变量命名约定:https://github.com/sendgrid/sendgrid-csharp/blob/master/SendGrid/Example/Example.cs#L41 使用 -name--city-,而 https://github.com/sendgrid/sendgrid-csharp/blob/master/SendGrid/Example/Example.cs#L157 使用 %name%%city%

我只是假设,变量替换基于简单的模式匹配,因此这些示例的对应模板包含相同的确切字符串。到目前为止,无论出于何种原因,这对我都不起作用。

string sendGridApiKey = ConfigurationManager.AppSettings["SendGridApiKey"].ToString();
var sendGrid = new SendGridAPIClient(sendGridApiKey);

string emailFrom = ConfigurationManager.AppSettings["EmailFrom"].ToString();
Email from = new Email(emailFrom);
string subject = "Supposed to be replaced. Can I get rid of this somehow then?";
string emaiTo = ConfigurationManager.AppSettings["EmailTo"].ToString();
Email to = new Email(emaiTo);
Content content = new Content("text/html", "Supposed to be replaced by the template. Can I get rid of this somehow then?");
Mail mail = new Mail(from, subject, to, content);
mail.TemplateId = "AC6A01BB-CFDF-45A7-BA53-8ECC54FD89DD";
mail.Personalization[0].AddSubstitution("<%subject%>", $"Your Report on {shortDateTimeStr}");
mail.Personalization[0].AddSubstitution("<%datetime%>", longDateTimeStr);
// Some code adds several attachments here

var response = await sendGrid.client.mail.send.post(requestBody: mail.Get());

请求已被接受并处理,但我收到的电子邮件仍然有主题行

“应该被替换了。那我可以摆脱这个吗?”

正文被原始模板内容替换,但变量也未被替换。我做错了什么?

【问题讨论】:

    标签: c# sendgrid sendgrid-api-v3 sendgrid-templates


    【解决方案1】:

    阅读How to Add Custom variables to SendGrid email via API C# and Template 问题和答案后,我意识到使用&lt;%foobar%&gt; 类型表示法是一个错误的决定。

    基本上它是 SendGrid 自己的符号,&lt;%subject%&gt; 意味着它们将替换您分配给 Mail subject 的内容,在我的情况下是 "Supposed to be replaced. Can I get rid of this somehow then?"。现在我在那里组装一个合适的主题。

    在模板主体本身中,我切换到{{foobar}} 变量表示法。尽管上面链接的问题的最后一个答案表明您必须将&lt;%body%&gt; 插入模板正文,但这不是必需的。没有它对我有用。我假设我可以在主题行中使用我自己的 {{foobar}} 变量,也可以通过适当的替换来代替 &lt;%subject%&gt;

    基本上,模板的默认状态是 &lt;%subject%&gt; 用于主题,&lt;%body%&gt; 用于正文,如果您不想要任何替换并通过API。

    如果我错了,请纠正我。

    string subject = $"Report on ${shortDateTimeStr}";
    string emaiTo = ConfigurationManager.AppSettings["EmailTo"].ToString();
    Email to = new Email(emaiTo);
    Content content = new Content("text/html", "Placeholder");
    Mail mail = new Mail(from, subject, to, content);
    mail.TemplateId = "AC6A01BB-CFDF-45A7-BA53-8ECC54FD89DD";
    mail.Personalization[0].AddSubstitution("{{datetime}}", longDateTimeStr);
    

    TL;DR:不要对自己的变量使用&lt;%foobar%&gt; 表示法,而是从其他十几种样式中选择一种。我读过的示例或文档都没有提到这一点。

    【讨论】: