Sendgrid v3: «Подстановки нельзя использовать с динамическими шаблонами» - PullRequest
0 голосов
/ 02 ноября 2018

Я пытаюсь обновить мой 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);
    }
}

Я получаю следующую ошибку:

ОШИБКА ROOT - java.io.IOException: запрос возвращенного состояния. Код 400Body: {"errors": [{"message": "Замены не могут использоваться с динамическими шаблонами", "field": "personalizations.0.substitutiontions " "помощь":" http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.substitutions"}]}

И я действительно не знаю, как поступить! Я читал документацию по sendgrid, но не смог ее получить.

Некоторые детали, которые могут помочь - Java8 - это язык - MAVEN для зависимостей - IntelliJ для IDE

Извините за возможные ошибки, это мой первый пост, а английский не мой основной язык. Спасибо!

1 Ответ

0 голосов
/ 07 ноября 2018

V3 API Sendgrid использует данные динамических шаблонов вместо подстановок.

Попробуйте вместо использования addSubstitution:

personalization.addDynamicTemplateData("{name2}",user.getName());
personalization.addDynamicTemplateData("{name1}",user.getName());

Источники:

https://github.com/sendgrid/sendgrid-java/blob/9bc569cbdb908dba609ed0d9d2691dff319ce155/src/main/java/com/sendgrid/helpers/mail/objects/Personalization.java

https://sendgrid.com/docs/ui/sending-email/how-to-send-an-email-with-dynamic-transactional-templates/

...