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
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
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
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.
<dependency>
<groupId>com.sendgrid</groupId>
<artifactId>sendgrid-java</artifactId>
<version>4.4.8</version>
</dependency>
2. Update your application.properties
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 EmailService.java
public interface EmailService {
public boolean sendResetPasswordEmail(String name);
}
4. Now create an email service file EmailServiceImpl.java
that implements our interface EmailService.java
import java.io.IOException;
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;
@Service("emailService")
public class EmailServiceImpl implements EmailService {
@Value("${sendgrid.api.key}")
private String sendGridApiKey;
@Value("${sendgrid.templateId}")
private String emailTemplateId;
private static final String fromEmailId = "no-reply@alagtech.com";
private static final String senderName = "ALAGTech";
private static final String toEmailId = "info@alagtech.com";
@Override
public boolean sendEmail(String name) {
SendGrid sg = new SendGrid(sendGridApiKey);
sg.addRequestHeader("X-Mock", "true");
Request request = new Request();
try {
Mail dynamicTemplate = buildDynamicTemplate(name);
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(dynamicTemplate.build());
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();
fromEmail.setName(senderName);
fromEmail.setEmail(fromEmailId);
mail.setFrom(fromEmail);
mail.setTemplateId(resetPassEmailTemplateId);
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));
mail.addPersonalization(personalization);
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
@Autowired
private EmailService emailService;
@GetMapping("/sendEmailAPI/{name}")
public Map sendEmailAPI(@PathVariable("name") String name) {
Map respMapList = new HashMap<>();
if(emailService.sendEmail(name)){
maplist.put("status", "200");
maplist.put("msg", "Email sent successfully");
}else{
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!