Sending Async Emails in Spring

I have a student taking my course that sent me the following question

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.

With the starter mail dependency in place we need to configure our mail server properties.

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.

We have one final task to make all of this work. Go to the main application class and add the @EnableAsync annotation.

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. You can grab the source for this application below.

Hi, I’m Dan Vega. I am a Software Engineer living just outside of one of my favorite places in the world, Cleveland, Ohio. I am a self-taught programmer who firmly believes that you can accomplish anything in this life if you put your mind to it, roll up your sleeves and are willing to put in the work.

I have been writing software for over 18+ years now and I use my knowledge, passion, and influence to help other developers achieve their goals. I teach online and currently, have over 30,000 students.

When I am not writing software, I have a number of things that really keep me busy. I love to read books, listen to podcasts and watch online courses. I have a real thirst for knowledge and it consumes me every single day of the week. I also love to run & lift heavy weights which keep me balanced throughout the week.

Please note: I reserve the right to delete comments that are offensive or off-topic.