Book Image

Mastering Spring Application Development

By : Anjana Mankale
Book Image

Mastering Spring Application Development

By: Anjana Mankale

Overview of this book

Table of Contents (19 chapters)
Mastering Spring Application Development
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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;
      }
      public void send(SimpleMailMessage simpleMessage) throws MailException {
        taskExecutor.execute(new MailRunnable(simpleMessage));
      }
    
      public void send(SimpleMailMessage[] simpleMessages) throws MailException ...