Implementing Email Services in a Spring Boot Application

Abishan Parameswaran
3 min readSep 20, 2023

--

Introduction

Email communication is an integral part of modern applications. Whether it’s sending notifications, account verifications, or newsletters, integrating email services into your Spring Boot application can enhance its functionality. In this article, we’ll explore how to implement email services with a Spring Boot application using JavaMailSender.

Prerequisites

Before diving into email service implementation, ensure you have the following prerequisites in place:

1. **Java and Spring Boot Knowledge:** A basic understanding of Java and Spring Boot is necessary for this tutorial.

2. **Spring Boot Project:** Create a Spring Boot project using your preferred IDE or Spring Initializer (https://start.spring.io/). Include the “Spring Web” and “Thymeleaf” (optional) dependencies.

Getting Started

1. **Add Spring Boot Starter Mail Dependency:**

In your project’s `pom.xml` (for Maven) or `build.gradle` (for Gradle), add the Spring Boot Starter Mail dependency:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2. **Configure Email Properties:**

Configure your email properties in the `application.properties` or `application.yml` file:

```properties
# Email Configuration
spring.mail.host=your_smtp_server_host
spring.mail.port=your_smtp_server_port
spring.mail.username=your_email_username
spring.mail.password=your_email_password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
```

Replace `your_smtp_server_host`, `your_smtp_server_port`, `your_email_username`, and `your_email_password` with your email provider’s SMTP server details and your email account credentials.

Implementing the Email Service

Now, let’s implement the code to send emails using the JavaMailSender provided by Spring Boot:

package com.eliteprogramming.noticationservice.service.impl;

import com.eliteprogramming.noticationservice.dto.EmailDto;
import com.eliteprogramming.noticationservice.dto.ErrorMessage;
import com.eliteprogramming.noticationservice.dto.Response;
import com.eliteprogramming.noticationservice.enums.ErrorCodeEnum;
import com.eliteprogramming.noticationservice.enums.ResponseMessage;
import com.eliteprogramming.noticationservice.service.EmailService;
import com.eliteprogramming.noticationservice.util.ENVConfig;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class EmailServiceImpl implements EmailService {

@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String fromEmail;
@Override
public Object sendMail(EmailDto emailDto) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();

MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

mimeMessageHelper.setFrom(fromEmail);
mimeMessageHelper.setTo(emailDto.getToList());
mimeMessageHelper.setSubject(emailDto.getSubject());
mimeMessageHelper.setText(emailDto.getBody());

javaMailSender.send(mimeMessage);

log.info("Message Sent Successfully to: {}", emailDto.getToList());
return new Response("Email Sent Successfully",emailDto.getToList(),ResponseMessage.SUCCESS);
}
catch (Exception e) {
log.error("sendEmail() | Error : {}", e.getMessage());
throw new RuntimeException(e);
}


}


}

This service class initializes the JavaMailSender with the email properties configured earlier and provides a method `sendEmail` for sending emails. You can inject this service into your controllers or services to send emails from different parts of your application.

Creating an Email Controller

To test the email service, create an email controller that exposes an endpoint for sending emails:

package com.eliteprogramming.noticationservice.controller;

import com.eliteprogramming.noticationservice.dto.EmailDto;
import com.eliteprogramming.noticationservice.dto.Response;
import com.eliteprogramming.noticationservice.dto.ResponseController;
import com.eliteprogramming.noticationservice.service.EmailService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashSet;
import java.util.Set;

@RestController
@RequestMapping("/emailService")
@Slf4j
@RequiredArgsConstructor
@CrossOrigin("*")
public class EmailController {
private final EmailService emailService;

@ApiIgnore
@PostMapping("/send")
@ApiOperation(value = "Send EMail", notes = "Send Email to the given Email Address")
@ApiResponse(code = 200, message = "Success", response = Response.class)
public ResponseEntity<Object> sendMail(@Valid @RequestBody EmailDto emailDto) {
log.info("HIT /send POST | Dto : {}", emailDto);
return ResponseEntity.ok(emailService.sendMail(emailDto));
}

}

In this controller, we inject the `EmailService` and create a POST endpoint at `/emailService/send` that accepts `toList` (recipient’s email address), `subject`, and `text` (email content) as request body.

Testing the Email Endpoint

You can now test the email sending functionality by making a POST request to `/emailService/send` with the recipient’s email address, subject, and email content.

Conclusion

Integrating email services into your Spring Boot application is essential for enhancing communication and user engagement. In this tutorial, we covered the essential steps, including configuring email properties and implementing the email service using JavaMailSender. With this integration, your application can send emails for various purposes, providing a seamless communication experience for your users.

You can refer the following GitHub repository for further Assistance: Follow this Link

I appreciate your time spent reading this blog, and I trust that you’ve gained insight into implementing SMS services within a Spring-Boot application. If you have any questions or uncertainties about this implementation, please don’t hesitate to leave a comment. I’ll do my best to assist you. Stay secure and take care.

--

--

Abishan Parameswaran

Software Engineer Intern at Arimac || Freelancer || Technical Blogger