I want to send infomation about users from database through email.
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT user from User user where user.reportDate >= :ago order by user.reportDate desc")
List<User> findAllWithDateAfter(@Param("ago") LocalDate ago);
}
Classic User entity:
@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
/getters and setters, etc
}
Service:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getUsersForRequiredDays(int days) {
LocalDate daysAgoDate = LocalDate.now().minusDays(days);
return badUtmMarksRepository.findAllWithDateAfter(daysAgoDate);
}
}
But I want to limit this query. If i'll retrieve more than 30 rows from this query, I want to divide it into parts. Instead of sending one email with 100 rows, I want to send four emails (30/30/30/10). I heard about pagination, but I don't know how to apply it for mail.
I'm sending emails on schedule:
public class ScheduledMailSenderService {
private final MailSenderService mailSender;
@Scheduled(cron = "${schedule.cron.update}")
public void send() {
log.info("Scheduled sending started");
try {
mailSender.send();
} catch (MessagingException | IOException | TemplateException e) {
log.error("Error occurred while sending email message:: {}", e.toString());
}
log.info("Scheduled sending finished");
}
}
Method send from senderService (in try block above):
public void send() throws MessagingException, IOException, TemplateException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
List<User> users = userService.getUsersForRequiredDays(interval); //im using info from db here
setMimeMessageSettings(mimeMessage, subject, emailTo, reportTable, from);
mailSender.send(mimeMessage);
}