0

I have a Spring MVC web Application with have to send mails for a lot of user actions which, at the first time, was made by a synchronous method.

If i make many actions (4-5) on sequence, the mail sender is not sending all mails but only some. I've tried with an @Async method but same result.

My method:

       @Async
   public Future<String> sendMail(MailParametersTO mailParams, MailTypeEnum type) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            message.setSubject(mailUtils.getMailSubject(mailParams.getSubjectParams(), type));
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(from);
            helper.setCc(mailParams.getCc().toArray(new String[0])); 
            helper.setTo(mailParams.getTo().toArray(new String[0]));
            helper.setText(mailUtils.getMailBody(mailParams.getBodyParams(), mailParams.getLink(), type), true);
         Thread.sleep(30000);
            mailSender.send(message);
        } catch (Exception e) {
         e.printStackTrace();
         return new AsyncResult<>("ERROR");
        }
      return new AsyncResult<>("OK");
    }   

Async configuration:

@Configuration
@EnableAsync(proxyTargetClass = true)
@EnableScheduling
public class AsyncConfig implements SchedulingConfigurer, AsyncConfigurer {

   @Bean
   public ThreadPoolTaskScheduler taskScheduler() {
      ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
      scheduler.setPoolSize(2);
      scheduler.setThreadNamePrefix("task-");
      scheduler.setAwaitTerminationSeconds(1200); // 20 minutes
      scheduler.setWaitForTasksToCompleteOnShutdown(true);
      return scheduler;
   }

   @Override
   public Executor getAsyncExecutor() {
      return this.taskScheduler();
   }

   @Override
   public void configureTasks(ScheduledTaskRegistrar registrar) {
      TaskScheduler scheduler = this.taskScheduler();
      registrar.setTaskScheduler(scheduler);
   }

   @Override
   public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
      return new SimpleAsyncUncaughtExceptionHandler();
   }
}

Anyone can help?

frsv9
  • 11
  • 3
  • How do you know that the email was not sent? Did you get an error message from the sending program? Or is it based on whether the recipient's mailbox has received the email? – life888888 Mar 01 '23 at 12:27
  • Maybe try FakeSMTP, run it, point your MailServer to localhost, change mail port to 2525 and test your mailer. – life888888 Mar 01 '23 at 12:32
  • @life888888 no errors are launched, but recipient received only some mails. – frsv9 Mar 01 '23 at 13:10

0 Answers0