Email configuration using Java +Springboot+Sendgrid+ GCP Pubsub

Aditya Nirmala
Nov 7 · 4 min read

Hello folks….

Lets see how to set up an email configuration using below stack trace.
1. Springboot
2. Java
3.SendGrid
4.GCP pubsub

Today’s requirement:
Send an email to user when he sign up for our application.

Step 1:
Create a send grid account and continue with free tier.
Now click on Templates -> Transactional -> create template
Give a name to template and save
Next click version-name hyperlink ->edit.
Here you can give your own html body with customized message you like.

Step 2:

Login to https://console.cloud.google.com/

Enable billing as we use billable components of GCP. Hopefully you will get some free credits worth $ 300 after successful set up of account …feels so cooool…

Click top left Navigation Menu -> pub/sub-> topics
Click create topic-> give a topic name -> create topic
Now create a subscription for same topic
Click on topic name-> create subscription->choose for custom app
Now give a subscription id, then check radio button push (we choose for push model).
Remember to give url endpoint to push messages of this configured topic.
This url can be our micro-service application or an app engine instance or cloud function.

Step 3:

Here comes our Java part. Lets dive into it.
Go to https://start.spring.io/

create a project with meaningful project artifact and group.
add the dependencies Spring web , GCP messaging, Lombok.
Now click generate project. Download ,extract and open in your own ide eclipse/ intellij editors.

This is our controller class
This is our service, template id would be a unique template id of send grid.
application.yml file

So now you have to create a service account for accessing pub-sub in IAM roles.
Now after creating a service account simple export it json. The json has to be base 64 encoded and place as value for key “encoded-key”.

Step 4:

Here comes implementation logic.
Go to https://start.spring.io/

create a project with meaningful project artifact and group.
add the dependencies Spring web .
Now click generate project. Download ,extract and open in your own ide eclipse/ intellij editors.

Now Go to https://mvnrepository.com/ look for send grid dependancy, add to your project dependencies.
We are good so far….are we ?
Now create a package controller, service in the application.
In service make necessary code changes.

write a controller class as the topic will push an event to our app engine app end point then our business logic gets triggered.

@Service
public class EmailPubSubService {
public String sendEmail(HttpServletRequest httpServletRequest) {
try {
JSONObject info = getData(httpServletRequest);
String fromEmail = info.get(“from”).toString().trim();
String fromName = info.get(“fromName”).toString().trim();
String toEmail = info.get(“to”).toString().trim();
String templateId = info.get(“templateId”).toString().trim();
Email from = new Email(fromEmail);
from.setName(fromName);
Email to = new Email(toEmail);
Mail mail = new Mail();
mail.setFrom(from);
mail.setTemplateId(templateId);
Personalization personalization = new Personalization();
personalization.addDynamicTemplateData(“emailId”, toEmail);
personalization.addTo(to);
mail.addPersonalization(personalization);
SendGrid sg =
new SendGrid(“GIVE THE SEND GRID ID”);
Request request = new Request();
request.setMethod(Method.POST);
request.setEndpoint(“mail/send”);
request.setBody(mail.build());
Response response = sg.api(request);
} catch (Exception ex) {
return “FAILURE”;
}
return “SUCCESS”;
}

private JSONObject getData(HttpServletRequest request) {
JSONObject dataObject = new JSONObject();
try {
String requestBody = request.getReader().lines().collect(Collectors.joining(“\n”));
JSONParser jsonParser = new JSONParser();

Object parsedObject = new Object();
parsedObject = jsonParser.parse(requestBody);
JSONObject jsonObject = null;
if (parsedObject instanceof JSONObject) {
jsonObject = (JSONObject) parsedObject;
Object mssgeObj = jsonObject.get(“message”);
if (mssgeObj instanceof JSONObject) {
JSONObject msgJsonObject = (JSONObject) mssgeObj;
String dataMsg =
new String(Base64.getDecoder().decode(msgJsonObject.get(“data”).toString()));
JSONParser parser = new JSONParser();
dataObject = (JSONObject) parser.parse(dataMsg);
}
}
} catch (Exception e) {
}
return dataObject;
}
}

Now configure ide with maven/gradle tools as you like.
open terminal/console
-gcloud init
follow the instructions shown on terminal and finish the step.
mvn package
mvn appengine:deploy

if everything fine you will see a deployment success message.
Now using a postman or any other api tool
call the initial request to send an email.

Please check your inbox.

Note: i have added a sample custom text for email, you can make changes as per your requirement.
Let me know if you have queries

HAPPY LEARNING :)

Aditya Nirmala

Written by

Am a technology enthusiastic,micro-service man,block-chain aspirant.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade