Home > Net >  when user posts email, I want to send mail only if more than 1 minute passed before same users send
when user posts email, I want to send mail only if more than 1 minute passed before same users send

Time:10-07

@RequestMapping( value = "/resendMail", method = RequestMethod.POST)
public ApiException sendMail(@Valid @RequestBody EmailRequest emailRequest) {
    ApiException response = null;
    User user = userRepository.findByEmail(emailRequest.getEmail());
    if( user!=null) {
        // If 1 minute passed do this.
        userService.sendVerificationEmail(user, user.getEmail());
        response = new ApiException("Link sent to this email,", null, HttpStatus.OK);
    }
}

This is my service. I want to do this if user didn't send request in 60 seconds:

SimpleMailMessage simpleMailMessage =new SimpleMailMessage();
simpleMailMessage.setFrom(from);
simpleMailMessage.setTo(to);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(content "http://localhost:8080/confirm-email?id="  user.getId());
try {
    mailSender.send(simpleMailMessage);
} catch (MailException mailException) {

}

CodePudding user response:

You can simply store lastEmailSentDate in UserEntity class as LocalDateTime.

Also create repository for this one and implement mail sending:

UserServiceImpl:

public boolean sendVerificationEmvail(UserEntity user){
    LocalDateTime last = user.getLastEmailSentDate();
    if(Objects.isNull(last) || !last.minusMinutes(1L).before(LocalDateTime.now())){
        return false;
    }

    user.setLastEmailSentDate(LocalDateTime.now());

    //Mail sending logic here

    userRepository.save(user);

    return true;
}

Controller:

@RequestMapping( value = "/resendMail", method = RequestMethod.POST)
public ApiException sendMail(@Valid @RequestBody EmailRequest emailRequest) {
    ApiException response = null;
    User user = userRepository.findByEmail(emailRequest.getEmail());
    if( user!=null) {
        if(userService.sendVerificationEmail(user)){
            response = new ApiException("Link sent to this email,", null, HttpStatus.OK);
        }
    }
}
  • Related