Building Synchronous Email Notification Systems in Spring Boot: A Step-by-Step Guide

ayshriv

Ayush Shrivastava

Posted on September 8, 2024

Building Synchronous Email Notification Systems in Spring Boot: A Step-by-Step Guide

Exploring the Fundamentals of Synchronous Email Delivery in Spring Boot Applications

A Spring Boot Synchronous Email Notification System interface displayed on a laptop screen. The design showcases an API dashboard with email notification logs, a section for setting email templates, and an overview of sent notifications. The color scheme is clean and modern, with shades of blue and white. In the background, there are visual elements representing email services like SMTP and JavaMailSender connecting through Spring Boot, depicted as a flow of emails between users and the server. The notification flow is shown synchronously, emphasizing real-time processing.

In today's fast-paced digital world, timely communication is crucial for any application. Whether it's a password reset, a welcome message, or an order confirmation, email notifications play a vital role in enhancing user experience. As developers, we often find ourselves in situations where sending an email notification from our Spring Boot application is not just a requirement but a necessity.

In this blog series, I'll guide you through the process of implementing email notifications in a Spring Boot application. We'll start with the basics—using a synchronous approach to send emails. This method ensures that the email is sent immediately during the execution of the request, providing instant feedback to the user.

While a synchronous approach is simple to implement and can be effective for smaller applications, it’s important to understand its limitations, particularly in high-traffic environments where performance can be impacted.

In this part, we’ll focus on setting up the project, configuring the necessary dependencies, and writing the code to send a basic email notification. By the end of this post, you'll have a working Spring Boot application capable of sending emails synchronously, setting the stage for more advanced topics in the upcoming parts of this series.

Project Setup

A Spring Boot Synchronous Email Notification System interface displayed on a laptop screen. The design showcases an API dashboard with email notification logs, a section for setting email templates, and an overview of sent notifications. The color scheme is clean and modern, with shades of blue and white. In the background, there are visual elements representing email services like SMTP and JavaMailSender connecting through Spring Boot, depicted as a flow of emails between users and the server. The notification flow is shown synchronously, emphasizing real-time processing.

Setting up Dependencies

A Spring Boot Synchronous Email Notification System interface displayed on a laptop screen. The design showcases an API dashboard with email notification logs, a section for setting email templates, and an overview of sent notifications. The color scheme is clean and modern, with shades of blue and white. In the background, there are visual elements representing email services like SMTP and JavaMailSender connecting through Spring Boot, depicted as a flow of emails between users and the server. The notification flow is shown synchronously, emphasizing real-time processing.

Dependency in your pom.xml file

Spring Boot Starter Data JPA

Artifact: spring-boot-starter-data-jpa
Description: This dependency simplifies data persistence using JPA (Java Persistence API). It provides everything needed for interacting with databases, including entities, repositories, and transactions. In this project, it allows you to save and retrieve user data (e.g., email logs, user information) from a MySQL database easily.

Spring Boot Starter Mail

Artifact: spring-boot-starter-mail
Description: This starter enables sending emails from your Spring Boot application. It includes the necessary components, such as JavaMailSender, to configure and send real-time email notifications for user activities like registration and order confirmations.

*Spring Boot Starter Web
*

Artifact: spring-boot-starter-web
Description: This dependency helps you build RESTful web services and serve web content. It brings in the essential libraries like Spring MVC for creating APIs. In this project, it enables the creation of endpoints to trigger email notifications via HTTP requests.

MySQL Connector

Artifact: mysql-connector-j
Description: This is the JDBC driver required for connecting your Spring Boot application to a MySQL database. It allows the application to interact with the database and perform actions like reading and writing data, such as storing email logs or user information.

Lombok

Artifact: lombok
Description: Lombok is a handy library that reduces boilerplate code by auto-generating common methods like getters, setters, and constructors. It’s marked as optional in this project, and its use can simplify code for data models like User or EmailLog.

Spring Boot Starter Test

Artifact: spring-boot-starter-test
Description: This dependency provides a comprehensive testing framework for Spring Boot applications. It includes libraries like JUnit, Mockito, and Spring Test for unit and integration testing. It helps ensure your email notification system is working as expected with automated tests.

Spring Boot Maven Plugin

Artifact: spring-boot-maven-plugin
Description: This plugin allows you to build and run your Spring Boot application from a Maven command. It simplifies packaging your project into an executable JAR file, making deployment easier. It excludes the Lombok dependency from the build process if necessary.

Configuring Application Properties

To connect your Spring Boot application to an email server, you can configure the application.properties or application.yml file with the necessary SMTP settings. Below is an example for each configuration format.

For application.properties

spring.application.name=Synchronous-Email-Notifier
server.port=8080

spring.datasource.url=jdbc:mysql://localhost:3306/synchronous_email_notifier
spring.datasource.username=root
spring.datasource.password=ayush@123

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=shri@gmail.com
spring.mail.password=
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
Enter fullscreen mode Exit fullscreen mode

For application.yml

spring:
  mail:
    host: smtp.example.com
    port: 587
    username: your-email@example.com
    password: your-email-password
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true

Enter fullscreen mode Exit fullscreen mode

Host: This is the SMTP server address. Replace smtp.example.com with your actual SMTP provider’s address (e.g., smtp.gmail.com for Gmail or smtp.mail.yahoo.com for Yahoo).

Port: Port 587 is typically used for sending emails over TLS (Transport Layer Security). If your email provider supports SSL, you can use port 465.

Username: The email address from which you’ll send the emails. Make sure to replace it with the actual email account.

Password: The password for your email account. For security reasons, if you’re using services like Gmail, it's recommended to use an App Password instead of your actual account password. Also, consider using environment variables for sensitive information like passwords.

SMTP Authentication: This enables authentication for your SMTP server, which is necessary when your email provider requires a valid username and password.

STARTTLS: This ensures that the connection to the email server is encrypted using TLS. It’s crucial for secure communication.

Project Setup

A Spring Boot Synchronous Email Notification System interface displayed on a laptop screen. The design showcases an API dashboard with email notification logs, a section for setting email templates, and an overview of sent notifications. The color scheme is clean and modern, with shades of blue and white. In the background, there are visual elements representing email services like SMTP and JavaMailSender connecting through Spring Boot, depicted as a flow of emails between users and the server. The notification flow is shown synchronously, emphasizing real-time processing.

User.java for storing the user mail and other information to database here we send the email to all the users which are present inside the database.

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    private String email;
    private String phoneNumber;
}
Enter fullscreen mode Exit fullscreen mode

UserService.java

public interface UserService {
    public void saveUser(User user);
}
Enter fullscreen mode Exit fullscreen mode

UserServiceImpl.java

public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public void saveUser(User user) {
        userRepository.save(user);
    }
}

Enter fullscreen mode Exit fullscreen mode

EmailController.java


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

    @Autowired
    EmailService emailService;

    @Autowired
    UserService userService;

    @PostMapping("/saveUser")
    public String saveUser(@RequestBody User user) {
        userService.saveUser(user);
        return "User saved successfully";
    }
}

Enter fullscreen mode Exit fullscreen mode

The EmailService interface defines a contract for sending emails in a Java application. It contains a method sendEmail, which takes three parameters: the recipient's email address (to), the email subject (subject), and the email content (body). Implementing this interface allows easy integration for email notifications.

package com.ayshriv.Synchronous_Email_Notifier.service;

public interface EmailService {
    void sendEmail(String to, String subject,String body);
}

Enter fullscreen mode Exit fullscreen mode

This EmailServiceImpl class implements the EmailService interface and provides the functionality to send emails using Spring's JavaMailSender. It uses a SimpleMailMessage to set the recipient (to), subject (subject), and body (text). The javaMailSender is automatically injected using Spring's @Autowired annotation. If any exceptions occur during the email-sending process, they are caught and logged to the console.

package com.ayshriv.Synchronous_Email_Notifier.service.impl;

import com.ayshriv.Synchronous_Email_Notifier.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    private JavaMailSender javaMailSender;

    public void sendEmail(String to, String subject,String body)
    {
        try {
            SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
            simpleMailMessage.setTo(to);
            simpleMailMessage.setSubject(subject);
            simpleMailMessage.setText(body);
            javaMailSender.send(simpleMailMessage);
        }
        catch (Exception exception)
        {
            System.out.println(exception.getMessage());
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

This EmailScheduler class is a Spring service that uses a scheduled task to send emails to all users in the database at regular intervals. The class works as follows:

It uses @Scheduled with a cron expression ("0 0/1 * 1/1 * ?") to run the fetchUsersAndSendEmail method every minute.
The method retrieves a list of all users from the UserRepository and sends an email to each one using the EmailService.
Each email sent has the subject "Demo text for email" and the body "Demo".

package com.ayshriv.Synchronous_Email_Notifier.schduler;

import com.ayshriv.Synchronous_Email_Notifier.entity.User;
import com.ayshriv.Synchronous_Email_Notifier.repository.UserRepository;
import com.ayshriv.Synchronous_Email_Notifier.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmailScheduler {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private EmailService emailService;

    @Scheduled(cron = "0 0/1 * 1/1 * ?")
    public void fetchUsersAndSendEmail()
    {
        List<User> users = userRepository.findAll();
        for (User user:users)
        {
            emailService.sendEmail(user.getEmail(),"Demo text for email","Demo");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

The EmailScheduler class in the Synchronous Email Notifier project automates sending marketing emails to users at specific intervals. Using Spring's @Scheduled annotation, it runs a task every minute, retrieving all users from the UserRepository and sending emails through the EmailService. This setup is ideal for businesses to automate the delivery of marketing emails, newsletters, or important notifications without manual intervention. The schedule can be adjusted using cron expressions, allowing flexibility in sending emails daily, weekly, or at any custom frequency, making it a powerful tool for time-based email campaigns.

Save User

Image description

Conclusion

The EmailScheduler class in the Synchronous Email Notifier project demonstrates a practical and efficient way to automate the process of sending emails to users. By leveraging Spring Boot's @Scheduled annotation and the flexibility of cron expressions, this class schedules the email-sending task to run every minute. The UserRepository fetches all user records, while the EmailService ensures that each user receives an email with predefined content.

This approach is highly useful for marketing purposes, where businesses need to send periodic emails like newsletters, promotional offers, or notifications at specific time intervals. The setup ensures that emails are consistently sent to all users without manual effort. This automation reduces the time and effort involved in communication processes while allowing marketers to focus on crafting effective campaigns.

The ability to customize the frequency of these emails, such as sending them daily, weekly, or monthly, makes this a versatile tool for marketing campaigns. Furthermore, you can modify the content dynamically to tailor the messaging for different users or occasions. Overall, this solution simplifies and streamlines the process of scheduled marketing emails, making it scalable and adaptable to various business needs.

You can access the full source code of the Synchronous Email Notifier project on GitHub. https://github.com/ishrivasayush/email-scheduling-application.git

This project demonstrates how to use Spring Boot to automate marketing emails with a scheduler. Feel free to explore and contribute!

💖 💪 🙅 🚩
ayshriv
Ayush Shrivastava

Posted on September 8, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related