Csa*_*oth 1 c# sendgrid sendgrid-api-v3 sendgrid-templates
我<%datetime%>在 SendGrid 模板中定义了一个变量。我根据这个命名约定决定遵循已经放置<%subject%>的主题行。我在示例中看到了不同的变量命名约定:https : //github.com/sendgrid/sendgrid-csharp/blob/master/SendGrid/Example/Example.cs#L41使用-name-and -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());
Run Code Online (Sandbox Code Playgroud)
请求已被接受并处理,但我收到的电子邮件仍有主题行
“应该被替换了。那我能不能把它去掉?”
正文由原始模板内容替换,但变量也未替换。我究竟做错了什么?
在阅读了如何通过 API C# 和模板问答将自定义变量添加到 SendGrid 电子邮件后,我意识到使用<%foobar%>类型表示法是一个错误的决定。
基本上它是 SendGrid 自己的符号,这<%subject%>意味着它们将替换您分配给 的内容Mail subject,在我的情况下是"Supposed to be replaced. Can I get rid of this somehow then?". 现在我在那里组装了一个合适的主题。
在模板主体中,我切换到{{foobar}}变量的表示法。尽管上面链接的问题的最后一个答案指出您必须插入<%body%>到模板正文中,但这不是必需的。它对我来说没有它。我假设我也可以{{foobar}}在主题行中使用我自己的变量,并进行适当的替换而不是<%subject%>.
基本上模板的默认状态是<%subject%>针对主题和<%body%>正文,如果您不想要任何替换并通过 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);
Run Code Online (Sandbox Code Playgroud)
TL;DR:不要<%foobar%>为您自己的变量使用符号,而是从十多种其他样式中选择一种。我读过的示例或文档都没有提到这一点。