Implementing Email Notifications in Spring Boot with SendGrid

Email notifications play a significant role in user engagement and communication for many applications. SendGrid is a popular cloud-based email delivery service that provides APIs for sending out transactional and marketing emails. In this post, we will go over how to integrate SendGrid with a Spring Boot application to send email notifications seamlessly.

What is SendGrid?

SendGrid is an email service provider that offers reliable email delivery services. It enables developers to send emails without having to manage their own email servers. Key features of SendGrid include:

  • Email APIs: Simple APIs to send and receive emails.
  • Template Management: Create dynamic email templates for personalized content.
  • Analytics: Gain insight into email performance, tracking opens, clicks, and bounces.

Setting Up SendGrid in Your Spring Boot Project

Follow these steps to integrate SendGrid for sending email notifications:

1. Create a SendGrid Account

If you don’t already have a SendGrid account, sign up for one at the SendGrid website. After signing up, create an API key from the settings section of your account.

2. Adding Dependencies

Add the following dependency to your pom.xml to include the SendGrid Java client:

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

3. Configuring Application Properties

Add your SendGrid API key to the application.properties file:

sendgrid.api.key=YOUR_API_KEY

Creating an Email Service

Create a service class responsible for sending emails using the SendGrid API:

import com.sendgrid.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;

@Service
public class EmailService {
    @Value("${sendgrid.api.key}")
    private String sendGridApiKey;

    public void sendEmail(String to, String subject, String body) throws IOException {
        Email from = new Email("your_email@example.com");
        Email toEmail = new Email(to);
        Content content = new Content("text/plain", body);
        Mail mail = new Mail(from, subject, toEmail, content);

        SendGrid sg = new SendGrid(sendGridApiKey);
        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;
        }
    }
}

Creating a REST Controller for Email Notifications

Next, create a REST controller to provide an endpoint for sending emails:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/email")
public class EmailController {

    @Autowired
    private EmailService emailService;

    @PostMapping("/send")
    public String sendEmail(@RequestParam String to,
                             @RequestParam String subject,
                             @RequestParam String body) {
        try {
            emailService.sendEmail(to, subject, body);
            return "Email sent successfully!";
        } catch (IOException e) {
            return "Failed to send email: " + e.getMessage();
        }
    }
}

Testing Your Email Service

Run your Spring Boot application and test the email-sending functionality using Postman or curl:

curl -X POST "http://localhost:8080/api/email/send?to=recipient@example.com&subject=Hello&body=This is a test email"

Conclusion

Integrating Spring Boot with SendGrid for sending email notifications allows developers to enhance their applications with vital communication features. With the ease of the SendGrid API, you can efficiently handle sending emails and customizing templates.

For further insights about leveraging Spring Boot with email services and complex integrations, explore the valuable resources offered by ITER Academy that will help you enhance your software development skills.

To learn more about ITER Academy, visit our website.

Scroll to Top