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
Open Spring Initializr in your browser.
Fill out the project details:
- Project: Choose
Maven Project
(orGradle
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).
- Project: Choose
Under Dependencies, select:
- Spring Web
- Spring Boot Starter Mail
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:
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
Step 5: Create the Controller (EmailController.java
)
Create a REST controller that will expose an endpoint to trigger the sending of emails.
EmailController.java
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:
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:
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.