【问题标题】:Send daily emails with Springboot - JHipster使用 Springboot 发送每日电子邮件 - JHipster
【发布时间】:2016-12-10 10:21:46
【问题描述】:

我想每天向我数据库的所有用户发送电子邮件。 我在后端使用 Springboot 和 JHipster。

在其余控制器中,我有一个 GET 请求(由 JHipster 自动创建):

/**
 * GET  /users : get all users.
 * 
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and with body all users
 * @throws URISyntaxException if the pagination headers couldnt be generated
 */
@RequestMapping(value = "/users",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(readOnly = true)
public ResponseEntity<List<ManagedUserDTO>> getAllUsers(Pageable pageable)
    throws URISyntaxException {
    Page<User> page = userRepository.findAll(pageable);
    List<ManagedUserDTO> managedUserDTOs = page.getContent().stream()
        .map(ManagedUserDTO::new)
        .collect(Collectors.toList());
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users");
    return new ResponseEntity<>(managedUserDTOs, headers, HttpStatus.OK);
}

我还有一个 MailService,它已经用于帐户验证和密码重置:

/**
* Service for sending e-mails.
* <p>
* We use the @Async annotation to send e-mails asynchronously.
* </p>
*/
@Service
public class MailService {

    private final Logger log = LoggerFactory.getLogger(MailService.class);

    private static final String USER = "user";
    private static final String BASE_URL = "baseUrl";

    @Inject
    private JHipsterProperties jHipsterProperties;

    @Inject
    private JavaMailSenderImpl javaMailSender;

    @Inject
    private MessageSource messageSource;

    @Inject
    private SpringTemplateEngine templateEngine;

    @Async
    public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
        log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
            isMultipart, isHtml, to, subject, content);

        // Prepare message using a Spring helper
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
            message.setTo(to);
            message.setFrom(jHipsterProperties.getMail().getFrom());
            message.setSubject(subject);
            message.setText(content, isHtml);
            javaMailSender.send(mimeMessage);
            log.debug("Sent e-mail to User '{}'", to);
        } catch (Exception e) {
            log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
        }
    }

    @Async
    public void sendActivationEmail(User user, String baseUrl) {
        user.setLangKey("en");
        log.debug("Sending activation e-mail to '{}'", user.getEmail());
        Locale locale = Locale.forLanguageTag(user.getLangKey());
        Context context = new Context(locale);
        context.setVariable(USER, user);
        context.setVariable(BASE_URL, baseUrl);
        String content = templateEngine.process("activationEmail", context);
        String subject = messageSource.getMessage("email.activation.title", null, locale);
        sendEmail(user.getEmail(), subject, content, false, true);
    }

    @Async
    public void sendCreationEmail(User user, String baseUrl) {
        log.debug("Sending creation e-mail to '{}'", user.getEmail());
        Locale locale = Locale.forLanguageTag(user.getLangKey());
        Context context = new Context(locale);
        context.setVariable(USER, user);
        context.setVariable(BASE_URL, baseUrl);
        String content = templateEngine.process("creationEmail", context);
        String subject = messageSource.getMessage("email.activation.title", null, locale);
        sendEmail(user.getEmail(), subject, content, false, true);
    }

    @Async
    public void sendPasswordResetMail(User user, String baseUrl) {
        log.debug("Sending password reset e-mail to '{}'", user.getEmail());
        Locale locale = Locale.forLanguageTag(user.getLangKey());
        Context context = new Context(locale);
        context.setVariable(USER, user);
        context.setVariable(BASE_URL, baseUrl);
        String content = templateEngine.process("passwordResetEmail", context);
        String subject = messageSource.getMessage("email.reset.title", null, locale);
        sendEmail(user.getEmail(), subject, content, false, true);
    }

}

我知道如何从前端发出请求并将其与后端连接起来,但在这里,我需要的是从后端到后端的请求。

我也不明白 Pageable 对象的用途以及如何创建它,因为它是一个接口:

public interface Pageable {

    int getPageNumber();

    int getPageSize();

    int getOffset();

    Sort getSort();

    Pageable next();

    Pageable previousOrFirst();

    Pageable first();

    boolean hasPrevious();
}

【问题讨论】:

    标签: spring-boot jhipster


    【解决方案1】:

    文泽,

    您所需要的只是使用调度的新服务。见下文摘录

    @Service
    @Transactional
    public class ScheduleService {
       //send mails daily at 1am
       @Scheduled(cron = "0 0 1 * * ?")
       public void sendDailyMails{
          //call userRepository.findAll
          //create mail content or use a template (e.g. Velocity)
          //for each user call MailService.sendMail 
          //passing content, to(user.getEmail()), from, etc;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-25
      • 1970-01-01
      • 2011-12-24
      • 2017-09-02
      • 2018-01-07
      • 1970-01-01
      • 2012-01-13
      • 2016-04-17
      • 2017-12-07
      相关资源
      最近更新 更多