2017-01-02 88 views
0

我在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%如何替換Sendgrid模板變量? (在C#中)

我只是假設變量替換是基於簡單模式匹配,因此這些示例的對應模板包含相同的確切字符串。儘管如此,無論出於何種原因,這對我來說都不起作用。

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

的請求被接受和處理,但是郵件我得到仍然有主題行

「應該被替換。我可以擺脫這個莫名其妙呢?」

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

回答

0

在閱讀How to Add Custom variables to SendGrid email via API C# and Template問題和答案我意識到使用<%foobar%>類型表示法是錯誤的決定。

基本上它是SendGrid自己的符號,並<%subject%>意味着他們會代替你分配什麼的Mailsubject,於我而言,這是"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%>符號來表示自己的變量,而是選擇從其他款式的打。我讀過的這些例子或文檔都沒有提到這一點。