AWS Simple Notification Service (SNS) provides a robust platform for sending notifications across various channels, including SMS and MMS. Let’s explore how to implement this functionality using Java within a Spring framework.

Prerequisites

  • AWS Account: An active AWS account is necessary.
  • AWS SDK for Java: Make sure you have the AWS SDK for Java integrated into your project. You can include it using Maven or Gradle.
  • IAM Permissions: Create an IAM user with appropriate permissions to publish SNS messages.
  • Spring Framework: Ensure your project is set up with the Spring framework.

Setting up AWS Credentials

  1. Access Key and Secret Key: Obtain your AWS access key ID and secret access key. Store them securely.

  2. Configure Credentials: There are multiple ways to configure your AWS credentials. A common approach is to set environment variables:

    export AWS_ACCESS_KEY_ID=your_access_key_id
    export AWS_SECRET_ACCESS_KEY=your_secret_access_key
    

Spring Service Implementation

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.MessageAttributeValue;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;

import java.util.Map;

@Service
public class SnsService {

    private final SnsClient snsClient;

    @Autowired
    public SnsService(SnsClient snsClient) {
        this.snsClient = snsClient;
    }

    public String sendSms(String phoneNumber, String message) {
        PublishRequest smsRequest = PublishRequest.builder()
                .message(message)
                .phoneNumber(phoneNumber)
                .build();

        PublishResponse smsResponse = snsClient.publish(smsRequest);
        return smsResponse.messageId();
    }

    public String sendMms(String phoneNumber, String message, String mediaUrl, String subject) {
        PublishRequest mmsRequest = PublishRequest.builder()
                .message(message)
                .phoneNumber(phoneNumber)
                .subject(subject)
                .messageAttributes(
                        Map.of("AWS.SNS.MMS.SMIL", MessageAttributeValue.builder()
                                        .dataType("String")
                                        .stringValue("<mms><body><par><img src=\"" + mediaUrl + "\" alt=\"image\" /></par></body></mms>")
                                        .build()
                        )
                )
                .build();

        PublishResponse mmsResponse = snsClient.publish(mmsRequest);
        return mmsResponse.messageId();
    }
}

Using the Spring Service

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SnsApplication implements CommandLineRunner {

    @Autowired
    private SnsService snsService;

    public static void main(String[] args) {
        SpringApplication.run(SnsApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        String phoneNumber = "+1234567890"; // Replace with the recipient's phone number
        String message = "This is a test SMS message from AWS SNS.";
        String mediaUrl = "https://example.com/image.jpg"; // Replace with your media URL
        String subject = "Test MMS";

        String smsMessageId = snsService.sendSms(phoneNumber, message);
        System.out.println("SMS Message ID: " + smsMessageId);

        String mmsMessageId = snsService.sendMms(phoneNumber, message, mediaUrl, subject);
        System.out.println("MMS Message ID: " + mmsMessageId);
    }
}

Explanation

  • Spring @Service Annotation: The SnsService class is annotated with @Service to mark it as a Spring service component.
  • SnsClient Injection: The SnsClient is injected into the service using constructor-based dependency injection (@Autowired).
  • Methods for SMS and MMS: The service provides sendSms and sendMms methods for sending messages.
  • Using the Service: The SnsApplication class demonstrates how to use the SnsService by autowiring it and calling its methods within the run method (triggered when the Spring Boot application starts).

Important Considerations

  • SnsClient Bean: You’ll need to configure an SnsClient bean in your Spring application context.
  • AWS Credentials: Make sure your AWS credentials are configured correctly.
  • Error Handling: Add proper error handling and exception management.
  • Opt-Out Mechanism: Provide recipients with a clear way to opt out.

Integrating AWS SNS into your Spring applications becomes straightforward with this approach. The Spring service encapsulates the messaging logic, promoting cleaner code and easier maintenance.


Discover more from GhostProgrammer - Jeff Miller

Subscribe to get the latest posts sent to your email.

By Jeffery Miller

I am known for being able to quickly decipher difficult problems to assist development teams in producing a solution. I have been called upon to be the Team Lead for multiple large-scale projects. I have a keen interest in learning new technologies, always ready for a new challenge.