Implementing Email Registration Functionality in Spring Boot Applications

To enable email funcctionality in a Spring Boot project, add the required dependencies to your pom.xml file:

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

<!-- Testing dependencies -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <scope>test</scope>
</dependency>

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

Confiugre email settings in you're application.yml file:

spring:
  mail:
    default-encoding: UTF-8
    host: smtp.gmail.com
    username: example@gmail.com
    password: your_app_password
    port: 587
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

Create a test class to verify email sending capabilities:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

@SpringBootTest
class EmailServiceTest {

    @Autowired
    private JavaMailSender mailSender;

    @Test
    void testEmailDelivery() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("example@gmail.com");
        message.setTo("recipient@example.com");
        message.setSubject("System Notification");
        message.setText("Your registration has been successfully completed.");
        
        mailSender.send(message);
    }
}

If dependency injection fails for JavaMailSender, create a configuration class:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

@Configuration
public class EmailConfig {
    
    @Bean
    public JavaMailSender configureMailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost("smtp.gmail.com");
        sender.setPort(587);
        sender.setUsername("example@gmail.com");
        sender.setPassword("your_app_password");
        
        Properties mailProps = sender.getJavaMailProperties();
        mailProps.setProperty("mail.transport.protocol", "smtp");
        mailProps.setProperty("mail.smtp.auth", "true");
        mailProps.setProperty("mail.smtp.starttls.enable", "true");
        
        return sender;
    }
}

When executing tests, ensure test methods use public access modifiers to avoid visibility issues.

Tags: Spring Boot Email Integration Java Configuration SMTP Setup

Posted on Thu, 09 Jul 2026 17:45:34 +0000 by Joe_Dean