ALAGTech blog Sending email with Send Grid dynamic template using Java Spring Boot

Sending email with Send Grid dynamic template using Java Spring Boot

This is a step by step guide to setup and use Sendgrid to send email via spring boot. This post is a step by step guide to achieve this integration so please be patient. For this demo purpose I will be creating a Spring-Boot Maven project, and will be exposing an API (sendEmail) that can be used to trigger the SendGrid Web API. But before we begin let's see what exaclty is SendGrid.

What is SendGrid?

SendGrid is a cloud-based SMTP provider that allows you to send email without having to maintain email servers. SendGrid manages all of the technical details, from scaling the infrastructure to ISP outreach and reputation monitoring to whitelist services and real time analytics.

Now let's jump right the integration part. Hope this helps you.

Steps to be done in Sendgrid

1. Login into your SendGrid account

2. In the setting menu click on API Keys.

3. Click on create API Key button

4. Give API Key a name, select Restricted Access radio button in the form

5. After you select Restricted Access button a bunch of options are displayed. Goto the Mail Send option activate mail send. For more on Sendgrid's API Keys click here

Creating an dynamic template with SendGrid. ALAGTech blog Sending email with Send Grid dynamic template using Java Spring Boot

6. Now click on Create & View button. And vola your API key has been created. Copy the API it will be only visible once.

7. Now that you have created you API Key. We will move on to creating creating a dynamic template.

8. In the Email API menu select Dynamic Templates

9. Click on Create a Dynamic Template. Give a name to it and then click create. Note down the Template Id

Creating an dynamic template with SendGrid. ALAGTech blog Sending email with Send Grid dynamic template using Java Spring Boot

10. Click on Add version button, and select a blank template and then choose Design Editor.

11. Give the template a name, subject etc. You can design the template as per your requirement.

12. Now this is the most important part of the whole integration process. All the data that will be sent to SendGrid v3 Web API needs to be sustituted in your dynamic template should be wrapped around in double curly brackets {{}}

13. Suppose our test data that sendgrid will receive will be {"user" : "Test User"}. Below snippet show how our dynamic template should look like

Creating an dynamic template with SendGrid. ALAGTech blog Sending email with Send Grid dynamic template using Java Spring Boot

Thats it!! You have completed setting up your SendGrid Account. Now lets move on to Spring-Boot part. Keep your SendGrid API key, Template Id handly we will require those now.

Steps to be done on Spring-Boot

1. For this demo I have created a Spring-Boot application with maven, add Sendgrid dependency in your pom.xml. You can check the latest dependency for SendGrid at mvnrepository click here.


2. Update your file as follows. Dont forget to update your API key and Template Id in the below code.

                    #SendGrid Details 
                    sendgrid.api.key=<Paste your API Key Here>
                    sendgrid.templateId=<Paste your Template Id Here>

3. Let's begin by creating an interface file

                  public interface EmailService {
	public boolean sendResetPasswordEmail(String name);

4. Now create an email service file that implements our interface


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.Email;
import com.sendgrid.helpers.mail.objects.Personalization;

public class EmailServiceImpl implements EmailService {
	private String sendGridApiKey;

	private String emailTemplateId;
	private static final String fromEmailId = "";
  private static final String senderName = "ALAGTech";
  private static final String toEmailId = "";
	public boolean sendEmail(String name) {

		SendGrid sg = new SendGrid(sendGridApiKey);
		sg.addRequestHeader("X-Mock", "true");

		Request request = new Request();

		try {
			Mail dynamicTemplate = buildDynamicTemplate(name);
			Response response = sg.api(request);

			if (response.getStatusCode() == 202) 
				return true;
		} catch (IOException ex) {
			// TODO
		return false;
	// API V3 Dynamic Template implementation
	public Mail buildDynamicTemplate(String name) throws IOException {

		Mail mail = new Mail();
		Email fromEmail = new Email();

		Personalization personalization = new Personalization();
		//This is the value that will be passed to the dynamic template in SendGrid
		personalization.addDynamicTemplateData("user", name);
		personalization.addTo(new Email(toEmailId));

		return mail;

5. Now you can bind the email service in your controller and use it to send email. Here's the snippet of the controller code

private EmailService emailService;

public  Map sendEmailAPI(@PathVariable("name") String name) {
	Map respMapList = new HashMap<>();
		maplist.put("status", "200");
		maplist.put("msg", "Email sent successfully");
		maplist.put("status", "500");
		maplist.put("msg", "Error occurred while sending email");
	return respMapList;

And there you go complete integration with SendGrid and Spring-Boot API. You can also visit SendGrid's git hub page click here.

Hope you enjoyed this blog. Please follow us on facebook , LinkedIn. Have a great day!