使用Quartz在特定时间发送电子邮件

时间:2016-10-20 15:57:01

标签: quartz-scheduler

您好我想请教您如何在 quartz 执行者中发送电子邮件。那是我的代码

public class SchedulerJob implements Job{
@EJB
private ParticipationTaskDao participationTaskDao;
public void sendEmail() throws AddressException, MessagingException {
    List<ParticipationTask> participantTasks=participationTaskDao.listParticipantTask();
    for(ParticipationTask participantTask:participantTasks){
        String subject="Task";
        String message="You take part to the task "+participant.getTask().getName()+" from "+participant.getTask().getDateStart()+" to "+participant.getTask().getDateEnd()+". Description:"
                + participantTask.getTask().getDescription();
        String receiver=participantTask.getUser().getEmail();
        System.out.println("Email sent initialisation... ");
        try {
        final String username="mymail@gmail.com";
        final String password="mypassword";
        String host = "smtp.gmail.com";
        String from = "mymail@gmail.com";
        String pass = "mypassword";
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "false");
        props.put("mail.debug", "true");

        Session session =  Session.getInstance(props, new GMailAuthenticator(username, password));
        MimeMessage message = new MimeMessage(session);
        Address fromAddress = new InternetAddress(from);
        Address toAddress = new InternetAddress(receiver);

        message.setFrom(fromAddress);
        message.setRecipient(Message.RecipientType.TO, toAddress);

        message.setSubject(subject);
        message.setText(message);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        message.saveChanges();
        Transport.send(message);
        transport.close();

  }catch(Exception ex){

        System.out.println("<html><head></head><body>");
        System.out.println("ERROR: " + ex);
        System.out.println("</body></html>");
  } 

        System.out.println(""Email sent successfully);
    }
}
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
    try {
        sendEmail();
    } catch (MessagingException e) {
        e.printStackTrace();
    }

}

}

当我启动服务器时,我什么都没看到,但如果我决定测试下面的代码,那么所有东西都能正常运行

public void execute(JobExecutionContext arg0) throws JobExecutionException {
    System.out.println("Quartz runs correctly");
}

0 个答案:

没有答案