1

大家好 !!我开发了一个小型应用程序,可以在单击提交按钮时将邮件发送到特定 ID。现在根据我的需要:

  1. 我必须在一天中的特定时间自动发送邮件。
  2. 为了澄清这一点,邮件应该在特定的时间发送到特定的 id。

所以我需要的是让我的过程自动进行。

任何建议将不胜感激..

protected void processRequest(HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ServletException {final String err = "/error.jsp";
    final String succ = "/success.jsp";


    String to = request.getParameter("to");
    String subject = request.getParameter("subject");
    String message = request.getParameter("message");
    String login = request.getParameter("login");
    String password = request.getParameter("password");

    try {
        Properties props = new Properties();
        props.setProperty("mail.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.starttls.enable", "true");

        Authenticator auth = new SMTPAuthenticator(login, password);

        Session session = Session.getInstance(props, auth);

        MimeMessage msg = new MimeMessage(session);
        msg.setText(message);
        msg.setSubject(subject);


        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        Transport.send(msg);

    } catch (AuthenticationFailedException ex) {
        request.setAttribute("ErrorMessage", "Authentication failed");

        RequestDispatcher dispatcher = request.getRequestDispatcher(err);
        dispatcher.forward(request, response);

    } catch (AddressException ex) {
        request.setAttribute("ErrorMessage", "Wrong email address");

        RequestDispatcher dispatcher = request.getRequestDispatcher(err);
        dispatcher.forward(request, response);

    } catch (MessagingException ex) {
        request.setAttribute("ErrorMessage", ex.getMessage());

        RequestDispatcher dispatcher = request.getRequestDispatcher(err);
        dispatcher.forward(request, response);
    }
    RequestDispatcher dispatcher = request.getRequestDispatcher(succ);
    dispatcher.forward(request, response);

}

private class SMTPAuthenticator extends Authenticator {

    private PasswordAuthentication authentication;

    public SMTPAuthenticator(String login, String password) {
        authentication = new PasswordAuthentication(login, password);
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return authentication;
    }
}

protected void doGet(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

protected void doPost(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}
}
4

4 回答 4

2

查看Quartz调度程序 Java 库。它具有广泛的配置和设置选项,并将涵盖从最简单的用例(例如,类似于标准 Java Timer)到复杂的类似 cron 的行为。

Quartz 是一种功能齐全的开源作业调度服务,可以与几乎任何 Java EE 或 Java SE 应用程序集成或一起使用——从最小的独立应用程序到最大的电子商务系统。Quartz 可用于创建简单或复杂的调度,以执行数十、数百甚至数万个作业;任务被定义为标准 Java 组件的作业,这些组件几乎可以执行任何您可以对其编程来执行的操作。

于 2012-09-14T09:05:07.240 回答
0

除了 Quartz 还有 Timer API ( http://java.sun.com/j2se/1.4.2/docs/api/java/util/Timer.html )

A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

您将计时器代码放入您添加到 web 应用程序的新 servlet。或者将您的代码添加到您的 web 应用程序中的现有 servlet。

还有很多其他开源调度 API ......

于 2012-09-14T09:42:57.270 回答
0
public class ClassExecutingTask {

long delayfornextstart = 60*60*24*7*1000; // delay in ms : 10 * 1000 ms = 10 sec.
LoopTask tasktoexecute = new LoopTask();
Timer timer = new Timer("TaskName");
public void start() throws ParseException, InterruptedException {
timer.cancel();
timer = new Timer("TaskName");
//@SuppressWarnings("deprecation")
//Date executionDate = new Date(2013-05-04); // no params = now
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("waiting for the rght day to come");
Date executionDate = sdf.parse("2014-04-03");

Date date1 = sdf.parse("2014-04-07");

Date date2 = sdf.parse("2014-04-07");
System.out.println(date1+"and"+date2);
long waitTill=getTimeDiff(date2,date1);
if(date2==date1)
{
    waitTill=0;
     System.out.println(waitTill);
}

   System.out.println(waitTill);
  Thread.sleep(waitTill);
timer.scheduleAtFixedRate(tasktoexecute, executionDate, delayfornextstart);
}

private class LoopTask extends TimerTask {
public void run() {
    ExcelReadExample EE=new ExcelReadExample();
    try {
        EE.ReadFile();//ur Mail code or the method which send the MAil
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

public static void main(String[] args) throws ParseException, InterruptedException {
ClassExecutingTask executingTask = new ClassExecutingTask();
executingTask.start();
}
public static long getTimeDiff(Date dateOne, Date dateTwo) {
    String diff = "";
    long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
    diff = String.format("%d hour(s) %d min(s)",     TimeUnit.MILLISECONDS.toHours(timeDiff),
            TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
    return timeDiff;
}


}
于 2014-04-07T12:06:33.330 回答
0

维卡斯,

您必须使用调度机制来启动电子邮件作业。此外,我建议您将邮件作业程序保留在单独的 java 类中,并在 servlet 中使用调度代码。

于 2012-09-14T11:16:16.193 回答