Sending Async Emails in Spring

It would be really cool to show how to send this email asynchronously. Because it's never a good idea to send any sort of notification synchronously.

I do agree with him in that there is no reason for us block program execution for something like sending an email. I am going to take this chance to walk you through sending email asynchronously using Spring Boot. Start off by creating a basic new Spring Boot project using the Spring Initializr from the web or your favorite IDE. We are going to select Web & Mail as dependencies.

By selecting web and mail as dependencies we should have these two starter dependencies included included in our build file.

The first thing we are going to do is create a controller. This controller is going to have a request mapping of signup-success. This method is going to create a user (just a simple POJO) and then try to send a notification using our notification service.

The Notification Service is where the real magic happens. At the start of our send notification method we are going to simulate a long process by using the sleep method. Notice that we have add the @Async annotation to the method that marks a method as a candidate for asynchronous execution.

Start the application and go to http://localhost:8080/signup-success. You will see the message "Thank you for registering with us." right away and in the console you will see the Sleeping/Sending/Sent messages printed out to the console. If you aren't familiar with Async this is where the real power comes in. The program is not blocking a task like sending an email and returns execution to the user while it performs that task in the background.

Dan Vega

I’m a Husband, Father, Curriculum Developer and maker of things from
Cleveland Ohio. I created this website as a place to document my
journey as I learn new things and share them with you. I have a real
passion for teaching and I hope that one of blog posts, videos or
courses helps you solve a problem or learn something new.