我正在尝试将我的 API 代码从 Sendgrid v2 更新到实际的 Sendgrid v3,所以我的代码过去看起来像这样:
public void sendCreatedUserEmail(User user) {
Email from = new Email(FROM);
from.setName(EMAIL_NAME);
String subject = "Hello" + user.getName();
Email to = new Email(user.getEmail());
Content content = new Content("text/html", "Something");
Mail mail = new Mail(from, subject, to, content);
mail.personalization.get(0).addSubstitution("{name1}", user.getName());
mail.personalization.get(0).addSubstitution("{name2}", user.getName());
mail.setTemplateId(USER_TEMPLATE_ID);
SendGrid sg = new SendGrid(SENDGRID_API_KEY);
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
} catch (IOException ex) {
logger.error(ex);
}
}
经过几个小时的研究,我将 v3 更改为: (为了更清晰的 View ,我将所有内容分开)
public void sendCreatedUserEmail(User user) {
Mail mail = new Mail();
Email from = new Email();
from.setName(EMAIL_NAME);
from.setEmail(FROM);
mail.setFrom(from);
String subject = "Hello, " + user.getName();
mail.setSubject(subject);
Personalization personalization = new Personalization();
Email to = new Email();
to.setEmail(user.getEmail());
to.setName(user.getName());
personalization.addTo(to);
personalization.setSubject(subject);
personalization.addSubstitution("{name2}",user.getName());
personalization.addSubstitution("{name1}",user.getName());
mail.addPersonalization(personalization);
Content content = new Content();
content.setType("text/html");
content.setValue("Something");
mail.addContent(content);
mail.setTemplateId(NEW_USER_TEMPLATE_ID);
SendGrid sg = new SendGrid(SENDGRID_API_KEY);
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (IOException ex) {
logger.error(ex);
}
}
我收到以下错误:
ERROR ROOT - java.io.IOException: 请求返回状态代码 400Body:{"errors":[{"message":"Substitutions may not be used with dynamic templating","field":"personalizations.0.substitutions ","帮助":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.substitutions "}]}
而且我真的不知道如何进行!我一直在阅读 sendgrid 文档,但我无法理解。
一些可能有帮助的细节 - Java8 是语言 - 用于依赖项的 MAVEN - IDE 的 IntelliJ
对于可能出现的错误,我深表歉意,这是我的第一篇文章,英语不是我的主要语言。谢谢!
最佳答案
Sendgrid API 的 V3 使用动态模板数据而不是替换。
试试这个而不是使用 addSubstitution
:
personalization.addDynamicTemplateData("{name2}",user.getName());
personalization.addDynamicTemplateData("{name1}",user.getName());
来源:
关于java - 发送网格 v3 : "Substitutions may not be used with dynamic templating",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111157/