Send Email with Azure Communication Services in Spring Boot: Step-by-Step Guide


This diagram represents the flow where:

  1. The user sends a request to the Spring Boot application via a POST request to /email/send.
  2. The Spring Boot application calls the sendEmail method in the EmailService.
  3. The EmailService uses the Azure Communication Services EmailClient to create an email message and sends it.
  4. The email is sent via Azure Communication Services and delivered to the recipient's inbox.

To send an email from a Spring Boot application using Azure Communication Services (ACS), follow the steps below:

Step 1: Create Azure Communication Services Resource

  1. Log in to the Azure portal and create an Azure Communication Services resource.
    • Go to Azure Portal -> Create a resource -> Communication Services.
    • Choose your region and create the service.
  2. After creating the resource, navigate to Keys under the Communication Services resource in the Azure portal. Copy the Connection String for your ACS resource. You’ll use this to authenticate the email client.

Step 2: Set Up Spring Boot Application

2.1. Create a Spring Boot Project

If you don't already have a Spring Boot project, create one by following these steps:

  • Go to Spring Initializr.
  • Select Maven or Gradle as the build tool, choose Java as the language, and select Spring Web dependency.
  • Generate the project and unzip it into your workspace.

2.2. Add Azure Communication Services SDK Dependency

In your pom.xml, add the Azure Communication Services Email SDK dependency:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-email</artifactId>
    <version>1.0.19</version> <!-- Use the latest version available -->
</dependency>

This will allow your Spring Boot application to interact with Azure Communication Services for email functionality.

Step 3: Configure application.properties

In your src/main/resources/application.properties file, add the ACS connection string:

azure.communication.connection-string=YOUR_ACS_CONNECTION_STRING

Replace YOUR_ACS_CONNECTION_STRING with the actual connection string you copied from the Azure portal.

Step 4: Implement Email Sending Logic

4.1. Create an Email Service Class

Now, create a service class to handle email sending using ACS.

import com.azure.communication.email.EmailClient;
import com.azure.communication.email.EmailClientBuilder;
import com.azure.communication.email.models.EmailMessage;
import com.azure.communication.email.models.EmailRecipient;
import com.azure.communication.email.models.EmailSender;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class EmailService {

    @Value("${azure.communication.connection-string}")
    private String connectionString;

    public void sendEmail(String recipientEmail, String subject, String content) {
        // Build the Email Client
        EmailClient emailClient = new EmailClientBuilder()
            .connectionString(connectionString)
            .buildClient();

        // Create the email message
        EmailMessage emailMessage = new EmailMessage(
            new EmailSender("sender@example.com"), // Use your verified sender email address
            subject,
            new EmailRecipient(recipientEmail),
            content
        );

        // Send the email
        emailClient.send(emailMessage);
        System.out.println("Email sent successfully to " + recipientEmail);
    }
}

This service class uses the Azure SDK to create an EmailClient that will send emails. The sendEmail method takes in the recipient email address, subject, and content, and sends the email.

4.2. Create a Controller to Trigger the Email

Create a simple REST controller to test the email sending functionality:

import com.example.demo.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

    @Autowired
    private EmailService emailService;

    @PostMapping("/send")
    public String sendEmail(@RequestParam String recipientEmail, @RequestParam String subject, @RequestParam String content) {
        emailService.sendEmail(recipientEmail, subject, content);
        return "Email sent successfully!";
    }
}

This controller has a simple POST endpoint /email/send where you can send an email by providing the recipient’s email address, subject, and content as request parameters.

Step 5: Test the Email Sending Functionality

  1. Run the Spring Boot Application: Start your Spring Boot application using the following command:

    mvn spring-boot:run
  2. Send an Email: You can now test the email sending functionality by making a POST request to the /email/send endpoint. You can use tools like Postman or curl to test this:

    • Using Postman:
      • Set the request method to POST.
      • URL: http://localhost:8080/email/send
      • Add the following parameters:
        • recipientEmail: recipient@example.com
        • subject: "Test Email"
        • content: "This is a test email sent via Azure Communication Services!"
    • Using curl:
      curl -X POST "http://localhost:8080/email/send?recipientEmail=recipient@example.com&subject=Test%20Email&content=This%20is%20a%20test%20email%20sent%20via%20Azure%20Communication%20Services!"
      

Step 6: Verify Email Delivery

After sending the request, check the recipient's inbox to verify that the email has been delivered. If the email is not delivered, make sure the sender email address is properly verified in the Azure portal.


Unlock Your Microservices Mastery for Only $9!

Get your copy now for just $9! and start building resilient and scalable microservices with the help of Microservices with Spring Boot 3 and Spring Cloud.

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