How to Send Email in Spring Boot Using JavaMailSender | Step-by-Step Guide

Here is a complete end-to-end guide on how to send an email in Spring Boot using JavaMailSender. This tutorial will take you from setting up your Spring Boot application to sending an email with the required configuration, code, and steps.


Step 1: Create a New Spring Boot Project Using Spring Initializr

  1. Open Spring Initializr in your browser.

  2. Fill out the project details:

    • Project: Choose Maven Project (or Gradle if preferred).
    • Language: Choose Java.
    • Spring Boot Version: Use the latest stable version.
    • Group: com.example
    • Artifact: email-demo
    • Name: email-demo
    • Description: A project to send emails using Spring Boot
    • Package Name: com.example.emaildemo
    • Packaging: Jar
    • Java Version: Select the version of Java (preferably 17 or newer).
  3. Under Dependencies, select:

    • Spring Web
    • Spring Boot Starter Mail
  4. Click the Generate button to download the ZIP file containing your project.

Step 2: Extract and Import the Project into Your IDE

  • Extract the downloaded ZIP file and open the folder in your preferred IDE (IntelliJ IDEA, Eclipse, etc.).

Step 3: Add Email Configuration in application.properties

After creating the Spring Boot project, configure the email settings in the src/main/resources/application.properties file. Here’s the sample configuration for Gmail’s SMTP server:

# Email configuration
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.debug=true

Replace your-email@gmail.com and your-email-password with your actual email credentials.

Note: You might need to enable "Less secure apps" access in Gmail or use App Passwords if you have 2-factor authentication enabled.

Step 4: Create the Email Service (EmailService.java)

Now, create a service to handle sending emails. Add the following code to the service class:

EmailService.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    // Method to send simple email
    public void sendSimpleEmail(String to, String subject, String body) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("your-email@gmail.com"); // Sender's email
            helper.setTo(to); // Recipient's email
            helper.setSubject(subject); // Subject of the email
            helper.setText(body); // Email body text

            javaMailSender.send(message); // Send email
            System.out.println("Email Sent Successfully!");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("Failed to send email");
        }
    }
}

Step 5: Create the Controller (EmailController.java)

Create a REST controller that will expose an endpoint to trigger the sending of emails.

EmailController.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmailController {

    @Autowired
    private EmailService emailService;

    // Endpoint to send email
    @GetMapping("/send-email")
    public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String body) {
        emailService.sendSimpleEmail(to, subject, body);
        return "Email sent successfully to " + to;
    }
}

Step 6: Run the Spring Boot Application

Now that everything is set up, you can run your application. If you are using Maven, you can run it from your IDE or the command line:

mvn spring-boot:run

Alternatively, if you are using IntelliJ IDEA or Eclipse, you can run the application by simply executing the main() method in the EmailDemoApplication class.

Step 7: Test the Email Sending

Once the application is running, you can test the email functionality by accessing the following URL:

http://localhost:8080/send-email?to=recipient-email@gmail.com&subject=Test+Email&body=This+is+a+test+email

Replace recipient-email@gmail.com with the recipient's actual email address.

Step 8: Verify the Email

Check the recipient's inbox to verify if the email has been sent successfully.

You’ve successfully created a Spring Boot application that sends emails using JavaMailSender. This guide walked you through setting up a Spring Boot project with the necessary dependencies, configuring the email settings, creating the email service and controller, and testing the functionality.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete