【问题标题】:SendGrid: templates and substitution tagsSendGrid:模板和替换标签
【发布时间】:2016-12-20 12:18:04
【问题描述】:

我创建了一个 sendgrid 模板,以便能够根据用户的信息构建我的电子邮件。到目前为止,它真的很简单:

<html>
<body>
  <div>&lt;%body%&gt;</div>  
  <div>Hi there&nbsp;: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,但是,我不知道如何:

  1. 设置模板版本。
  2. 添加令牌替换。

另一方面:

  1. section tagssubstitution tags&lt;%subject%&gt;&lt;%body%&gt; 标签之间有什么区别?

拜托,我真的看过文档。到目前为止,我还无法理解我提出的所有内容。

【问题讨论】:

标签: java sendgrid


【解决方案1】:

我想做类似的事情,但我无法通过一个请求找到一种方法。

将使用的模板始终是“活动”模板,因此,要选择不同的版本,您必须首先调用模板/版本端点并“激活”它。

假设您使用的是 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);
}

要检索模板版本列表,你需要调用templates endpoint...然后版本的使用变得有点乏味xD。

对于替换,您必须构建一个 Personalization 对象:

Personalization obj = new Pesrsonalization();
obj.addSubstitution("tag", "value");
// Etc.

Personalization 类非常有用,因为它可以保存收件人(CC、BCC 和 TO)和其他数据。

标签被替换为您在 mail.body 中发送的任何内容,而 被替换为在邮件中设置的主题Personalization 对象(或 mail.subject)。与任何其他标签的唯一区别是这些标签不需要通过 Personalization 对象进行设置。

顺便说一句,主题可以包含其他标签,这些标签也将被替换。

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2016-07-26
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 2016-03-12
    • 1970-01-01
    相关资源
    最近更新 更多