簡體   English   中英

如何替換Sendgrid模板變量? (在C#中)

[英]How to substitute Sendgrid template variables? (in C#)

我在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());

該請求已被接受並處理,但我收到的電子郵件仍然包含主題行

“應該被替換。那我能以某種方式擺脫它嗎?”

主體被原始模板內容替換,但變量也未被替換。 我究竟做錯了什么?

在閱讀了如何通過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);

TL; DR:不要對您自己的變量使用<%foobar%>表示法,而應從其他數十種樣式中選擇一種。 我閱讀的所有示例或文檔都沒有提到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM