[英]SendGrid: templates and substitution tags
我創建了一個sendgrid模板,以便能夠根據用戶信息構建電子郵件。 到現在為止,這很簡單:
<html>
<body>
<div><%body%></div>
<div>Hi there :username!</div>
<div>Please, click on here to complete Accoung Activation: :activation</div>
<div>Please, bear with us.</div>
</body>
</html>
到目前為止,我一直在尋找可以替換令牌( :username
和:activation
)的方法。
不過,我不太了解如何在Java上構建它。 到目前為止,我已經能夠編寫以下代碼以便發送帶有模板的電子郵件:
String activationUri = "http://activation uri.sample.com/activation";
String address = "sample@sample.com";
Email from = new Email("no-reply@facetz.zone");
String subject = "Account activation mail request";
Email to = new Email(address);
Content content = new Content("text/plain", activationUri);
Mail mail = new Mail(from, subject, to, content);
mail.setTemplateId("7928c2b2-c5a9-4918-a035-db5b7aae532b");
SendGrid sg = new SendGrid("api_key");
Request request = new Request();
try {
request.method = Method.POST;
request.endpoint = "mail/send";
request.body = mail.build();
Response response = sg.api(request);
} catch (IOException ex) {
throw MailGenerationException.create(address, ex);
}
如您所見,盡管如此,我已經設置了templateId
,但我無法獲得如何:
另一方面:
section tags
和substitution tags
以及<%subject%>
和<%body%>
標簽之間有什么區別? 拜托,我真的看過文檔。 到目前為止,我還無法理解我提出的所有內容。
我一直想做類似的事情,但是我找不到一種方法可以處理一個請求。
將使用的模板始終是“活動的”模板,因此,要選擇其他版本,必須首先調用模板/版本端點並“激活”它。
假設您使用的是API版本3,那么您將執行以下操作(在實際發送電子郵件之前):
Request request = new Request();
try {
request.method = Method.PATCH;
request.endpoint = "templates/" + templateId + "/versions/" + versionId;
request.body = "{\"active\": \"1\"}";
Response response = sg.api(request);
if (response.status == 200)
// success
else
// failure
} catch (IOException ex) {
throw MailGenerationException.create(address, ex);
}
要檢索模板版本列表,您需要調用模板端點 ...然后使用版本會變得有點乏味。
對於替換,您必須構建一個Personalization對象:
Personalization obj = new Pesrsonalization();
obj.addSubstitution("tag", "value");
// Etc.
個性化類非常有用,因為它可以容納收件人(CC,BCC和TO)和其他數據。
<%body%>標記將替換為您在mail.body中發送的內容,而<%subject%>則替換為在Personalization對象(或mail.subject)中設置的主題。 與任何其他標簽的唯一區別是不需要通過Personalization對象設置這些標簽。
順便說一下,主題可以包含其他標簽,這些標簽也將被替換。
希望這對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.