1

Hello Guys !! I developed a small application to send mail to particular id on clicking submit Button. Now As per my needs:

  1. I have to send mail automatically at particular time of day.
  2. To clarify this ,mail Should be sent to particular id at particular time .

So what I need is to make my process automatically .

Any suggestions will be highly appreciated..

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);
}
}
Misha Zaslavsky
  • 4,808
  • 10
  • 44
  • 95
  • If you are on linux, Google `cron jobs`. If you are on Windows Google `Scheduled Tasks`. – RB. Sep 14 '12 at 09:04

4 Answers4

2

Check out the Quartz scheduler Java library. It has a wide range of configuration and setup options, and will span use-cases from the most simple (e.g. analogous to a standard Java Timer) to complex cron-like behaviour.

Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java EE or Java SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may execute virtually anything you may program them to do.

Brian Agnew
  • 254,044
  • 36
  • 316
  • 423
  • Thank you Sir for ur quick response.I went through ur link but dont know how to use quartz in my app .plz guide me where and how to use Quartz ... –  Sep 14 '12 at 09:28
  • Thank you Guys for Ur Suggestions .I completed my task by the use of Timer API... Thanx again !!11 –  Sep 14 '12 at 11:46
  • Vikas, do not use `Timer` in Java EE web applications! – BalusC Sep 16 '12 at 15:08
0

In addition to Quartz there is also the 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.

You put the timer code into a new servlet that you add to your webapp. Or add your code to an existing servlet in your webapp.

There are plenty of other open source scheduling API's as well....

MaVRoSCy
  • 16,907
  • 14
  • 76
  • 116
0

Vikas,

You have to use a scheduling mechanism to start the e-mail job. Additionally I would suggest you to keep the mail-job program in a separate java class and use Scheduling code in the servlet.

Binu
  • 120
  • 6
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;
}


}
Companjo
  • 1,738
  • 17
  • 22
Bassu
  • 1