'Created sendgrid email template, how to call it from Java

I have created email template in sendgrid - with substitutable values;

I get the JSON payload (contains substitute values) for processing email from rabbitMQ queue. My question is how to call the sendgrid email template from Java?



Solution 1:[1]

I found the solution, the way to call sendgrid template and email through sendgrid as below:

SendGrid sendGrid = new SendGrid("username","password"));
SendGrid.Email email = new SendGrid.Email();

//Fill the required fields of email
email.setTo(new String[] { "[email protected]"});
email.setFrom("[email protected]");
email.setSubject(" ");
email.setText(" ");
email.setHtml(" ");

// Substitute template ID
email.addFilter(
    "templates",
    "template_id",
    "1231_1212_2323_3232");

//place holders in template, dynamically fill values in template
email.addSubstitution(
     ":firstName",
     new String[] { firstName });
email.addSubstitution(
     ":lastName",
     new String[] { lastName });

// send your email
Response response = sendGrid.send(email);

Solution 2:[2]

Here is an example from last API spec:

import com.sendgrid.*;
import java.io.IOException;

public class Example {
  public static void main(String[] args) throws IOException {
    Email from = new Email("[email protected]");
    String subject = "I'm replacing the subject tag";
    Email to = new Email("[email protected]");
    Content content = new Content("text/html", "I'm replacing the <strong>body tag</strong>");
    Mail mail = new Mail(from, subject, to, content);
    mail.personalization.get(0).addSubstitution("-name-", "Example User");
    mail.personalization.get(0).addSubstitution("-city-", "Denver");
    mail.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932");

    SendGrid sg = new SendGrid(System.getenv("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) {
      throw ex;
    }
  }
}

https://github.com/sendgrid/sendgrid-java/blob/master/USE_CASES.md

Solution 3:[3]

This is my working soloution .

import com.fasterxml.jackson.annotation.JsonProperty;
import com.sendgrid.*;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class MailUtil {
    public static void main(String[] args) throws IOException {
        Email from = new Email();
        from.setEmail("fromEmail");
        from.setName("Samay");
        String subject = "Sending with SendGrid is Fun";
        Email to = new Email();
        to.setName("Sam");
        to.setEmail("ToEmail");
        DynamicTemplatePersonalization personalization = new DynamicTemplatePersonalization();
        personalization.addTo(to);
        Mail mail = new Mail();
        mail.setFrom(from);
        personalization.addDynamicTemplateData("name", "Sam");
        mail.addPersonalization(personalization);
        mail.setTemplateId("TEMPLATE-ID");
        SendGrid sg = new 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) {
            throw ex;
        }
    }
    private static class DynamicTemplatePersonalization extends Personalization {

        @JsonProperty(value = "dynamic_template_data")
        private Map<String, String> dynamic_template_data;

        @JsonProperty("dynamic_template_data")
        public Map<String, String> getDynamicTemplateData() {
            if (dynamic_template_data == null) {
                return Collections.<String, String>emptyMap();
            }
            return dynamic_template_data;
        }

        public void addDynamicTemplateData(String key, String value) {
            if (dynamic_template_data == null) {
                dynamic_template_data = new HashMap<String, String>();
                dynamic_template_data.put(key, value);
            } else {
                dynamic_template_data.put(key, value);
            }
        }

    }
} 

Solution 4:[4]

Recently Sendgrid upgraded the Maven version v4.3.0 so you don't have to create additional classes for dynamic data content. Read more from this link https://github.com/sendgrid/sendgrid-java/pull/449

Solution 5:[5]

If you're doing a spring-boot maven project, You'll need to add the sendgrid-java maven dependency in your pom.xml. Likewise, in your application.properties file under resource folder of the project, add SENDGRID API KEY AND TEMPLATE ID under attributes such as spring.sendgrid.api-key=SG.xyz and templateId=d-cabc respectively.

Having done the pre-setups. You can create a simple controller class as the one given below:

Happy Coding!

@RestController
@RequestMapping("/sendgrid")
public class MailResource {

    private final SendGrid sendGrid;

    @Value("${templateId}")
    private String EMAIL_TEMPLATE_ID;

    public MailResource(SendGrid sendGrid) {
        this.sendGrid = sendGrid;
    }

    @GetMapping("/test")
    public String sendEmailWithSendGrid(@RequestParam("msg") String message) {

        Email from = new Email("[email protected]");
        String subject = "Welcome Fonesal Unit to SendGrid";
        Email to = new Email("[email protected]");
        Content content = new Content("text/html", message);

        Mail mail = new Mail(from, subject, to, content);

        mail.setReplyTo(new Email("[email protected]"));
        mail.setTemplateId(EMAIL_TEMPLATE_ID);

        Request request = new Request();
        Response response = null;


        try {
            request.setMethod(Method.POST);
            request.setEndpoint("mail/send");
            request.setBody(mail.build());

            response = sendGrid.api(request);

            System.out.println(response.getStatusCode());
            System.out.println(response.getBody());
            System.out.println(response.getHeaders());
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }

        return "Email was successfully sent";
    }

}

Solution 6:[6]

This is based on verision com.sendgrid:sendgrid-java:4.8.3

        Email from = new Email(fromEmail);
        Email to = new Email(toEmail);
        String subject = "subject";

        Content content = new Content(TEXT_HTML, "dummy value");

        Mail mail = new Mail(from, subject, to, content);

        // Using template to send Email, so subject and content will be ignored
        mail.setTemplateId(request.getTemplateId());

        SendGrid sendGrid = new SendGrid(SEND_GRID_API_KEY);
        Request sendRequest = new Request();

        sendRequest.setMethod(Method.POST);
        sendRequest.setEndpoint("mail/send");
        sendRequest.setBody(mail.build());

        Response response = sendGrid.api(sendRequest);

You can also find fully example here: Full Email object Java example

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Igor Artamonov
Solution 2 Zaur_M
Solution 3
Solution 4 Athar
Solution 5 bijayshrestha
Solution 6 sendon1982