Sending scheduled mail via Spring Boot Rest api

Viewed 417

I am fairly new to spring boot. I wanna create a spring boot Rest API to send a mail in preferred - the preferences stored in the mongoDB.- by the user at certain time intervals. But I am very confused about how can I achieve this! Can anybody help me?

2 Answers

In my opinion you have two options:

  1. Use Spring capabilities to programmatically schedule the task to the desired date and time. I would suggest you take a look at https://docs.spring.io/spring-framework/docs/5.0.0.M5/spring-framework-reference/html/scheduling.html. Take special attention to the TaskScheduler interface;
  2. You handle this on your own by checking, from time to time (say every minute), if there are any emails to be sent in that time period.

I would prefer the first one because you would rely on battle-tested features instead of trying to build them on your own.

You can use scheduler cron to call method at some interval or use fixed delay in spring boot @scheduled. and use SMTP method to send message on mail.

    @Scheduled(fixedRate = 18000)
    public void sendmailviaSMTP() {
      // Code to send message via SMTP
    }

Reference:

  1. Scheduling Task
  2. Cron Expressions
  3. Send Email with SMTP
Related