Sending emails with SendGrid and spring boot

Hamdi Bouallegue
Apr 23 · 4 min read

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 the technical details, from scaling the infrastructure to ISP outreach and reputation monitoring to whitelist services and real-time analytics.

Create an account :

Then log in to your account :

You will see something like this.

Create Spring boot application :

https://start.spring.io/

Dependencies: Spring Web, and Spring Boot DevTools.

After downloading and unzipping the project, add this dependency:

<dependency><groupId>com.sendgrid</groupId><artifactId>sendgrid-java</artifactId><version>4.0.1</version></dependency>

See pom.xml below :

Create a Single Sender Verification :

Navigate to https://app.sendgrid.com/settings/sender_auth/senders :

After filling in all the inputs, click on Create button. Then you will receive an activation email.

Sending emails :

1. Get the API key :

From the dashboard click on Email API then the integration guide.

Chose the Web API

And then java :

Enter a Key name and click Create button

Copy your API key.

2. Create a service :

3. Create a rest controller :

4. Test the API :

On postman

post: http://localhost:8080/api/send-text

You will receive an email Verify your spam emails.

Sending email with dynamic templates :

SendGrid enables us to use templates or create our own templates.

1. Let’s create a template :

Navigate here

click on SendGrid email design we will choose a prebuilt one.

I choose Off Grid Adventures.

then select Design editor

Now let’s add some modifications to our template.

Click on Welcome to the family and change the text to

Welcome {{first_name}}

The {{first_name}} means that it is a variable and will be changed dynamically using code.

Click preview to see the output

Click show test data

The template changed dynamically.

Now Click on the save button then the back arrow

Copy the template id.

2. Update the MailService:

3. Update the rest controller :

@PostMapping("/send")public String sendWithTemplate() throws IOException {return mailService.send();}

4. Test the new API :

On postman

post: http://localhost:8080/api/send

You will receive an email with our template.

Verify your spam emails.

Last word :

You can find the source code here :

If you enjoyed this article, please clap it up 👏 and share it so that others can find it! Follow me to get more of me 😄.

Javarevisited

Medium’s largest Java publication, followed by 12700+ programmers. Follow to join our community.