Sending Spring mails over a different thread

There are other options for sending Spring mail asynchronously. One way is to have a separate thread to the mail sending job. Spring comes with the taskExecutor package, which offers us a thread pooling functionality.

  1. Create a class called MailSenderAsyncService that implements the MailSender interface.
  2. Import the org.springframework.core.task.TaskExecutor package.
  3. Create a private class called MailRunnable. Here is the complete code for MailSenderAsyncService:
    public class MailSenderAsyncService implements MailSender{ @Resource(name = "mailSender") private MailSender mailSender; private TaskExecutor taskExecutor; @Autowired public MailSenderAsyncService(TaskExecutor taskExecutor){ this.taskExecutor = taskExecutor; ...

Get Mastering Spring Application Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.