我正在尝试将我的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更改为: (为了确保画面清晰,我竭尽所能)
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);
}
}
我收到以下错误:
错误根-java.io.IOException:请求返回的状态代码为400Body:{“ errors”:[{“ message”:“替换不能与动态模板一起使用”,“ field”:“ personalizations.0.substitutions “,” help“:” http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.substitutions“}]}
我真的不知道该如何进行!我一直在阅读sendgrid文档,但无法理解。
一些可能有用的细节 -Java8是语言 -依赖 -适用于IDE的IntelliJ
很抱歉可能出现的错误,这是我的第一篇文章,英语不是我的主要语言。谢谢!
答案 0 :(得分:3)
Sendgrid API的V3使用动态模板数据代替替代。
尝试使用此方法,而不要使用addSubstitution
:
personalization.addDynamicTemplateData("{name2}",user.getName());
personalization.addDynamicTemplateData("{name1}",user.getName());
来源:
答案 1 :(得分:1)
尝试:
personalization.addDynamicTemplateData("name2",user.getName());
personalization.addDynamicTemplateData("name1",user.getName());