Send Emails with Spring Boot and Google Cloud: Complete Guide with SendGrid Integration

Workflow of sending an email in a Spring Boot application integrated with Google Cloud's SendGrid service

Explanation of the Diagram

  1. User Interaction: A user sends an HTTP request to the Spring Boot application to trigger the email-sending process.
  2. Application Processing: The Spring Boot app validates the input and prepares the email request.
  3. API Integration: The app sends the email request to the SendGrid API.
  4. SendGrid Processing: SendGrid processes the email request and sends the email to the recipient.
  5. Response Handling: SendGrid returns the status, and the Spring Boot app relays this back to the user.

Here’s an end-to-end example of how to send emails in a Spring Boot application using Google Cloud services, specifically integrating with SendGrid, which is a recommended solution for transactional email in Google Cloud.


1. Set Up SendGrid on Google Cloud

  1. Enable SendGrid:

    • Go to the Google Cloud Marketplace - SendGrid.
    • Click "Subscribe" and choose a pricing plan.
  2. Create an API Key:

    • Log in to the SendGrid Dashboard.
    • Navigate to Settings > API Keys.
    • Click "Create API Key", provide a name, and assign permissions (e.g., Full Access).
    • Copy the API key (you’ll need it later).

2. Spring Boot Project Setup

2.1 Add Dependencies

Add the following dependencies to your pom.xml:

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- SendGrid Java Library -->
    <dependency>
        <groupId>com.sendgrid</groupId>
        <artifactId>sendgrid-java</artifactId>
        <version>4.9.3</version>
    </dependency>
</dependencies>

2.2 Configure SendGrid API Key

Add the API key to your application.properties or application.yml:

application.properties:

sendgrid.api.key=YOUR_SENDGRID_API_KEY

application.yml:

sendgrid:
  api:
    key: YOUR_SENDGRID_API_KEY

3. Create Email Service

Create a service to handle email sending:

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 String sendEmail(String toEmail, String subject, String body) {
        Email from = new Email("your-email@example.com"); // Replace with your verified SendGrid email
        Email to = new Email(toEmail);
        Content content = new Content("text/plain", body);
        Mail mail = new Mail(from, subject, to, 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);
            return "Email sent with status code: " + response.getStatusCode();
        } catch (IOException ex) {
            return "Error sending email: " + ex.getMessage();
        }
    }
}

4. Create a REST Controller

Create a controller to expose an API for sending emails:

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

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

    @Autowired
    private EmailService emailService;

    @PostMapping("/send")
    public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String body) {
        return emailService.sendEmail(to, subject, body);
    }
}

5. Test the Application

  1. Start your Spring Boot application.
  2. Use a tool like Postman or curl to test the API:

Request:

POST http://localhost:8080/api/emails/send
Content-Type: application/x-www-form-urlencoded

to=recipient@example.com
subject=Hello from Spring Boot
body=This is a test email sent via Google Cloud and SendGrid!

6. Deploy to Google Cloud (Optional)

6.1 Dockerize Your Application

Create a Dockerfile:

FROM openjdk:17-jdk-slim
VOLUME /tmp
COPY target/*.jar app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]

Build the Docker image:

mvn clean package
docker build -t spring-boot-email-app .

6.2 Deploy to Google Cloud Run

  1. Push the Docker image to Google Container Registry (GCR) or Artifact Registry.
  2. Deploy to Google Cloud Run.

7. Monitor Email Logs

Log in to the SendGrid Dashboard to monitor email delivery, bounces, or errors.

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example