0

I am working on a web_application sing Java,servlets,JSP and using apache Tomcat as application server

What I have done

  • i have created a UI where user is selecting mail Ids (they can select more than one)
  • And when user is clicking on send button i am triggering my java class and sending the mail

Now What i have to do

  • Now i have to do this dynamically,every night at 12:00 O'clock i have to send mail to some particular users

  • User to whom i have to send mail i am getting that mail id from login query so that is not an issue

  • I just want to know how can I send mail when it is midnight 12:00 O'clock

Codding I have done till now

servlet class

public class EmailSendingServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
private String host;
private String port;
private String user;
private String pass;

public void init() {

    ServletContext context = getServletContext();
    host = context.getInitParameter("host");
    port = context.getInitParameter("port");
    user = context.getInitParameter("user");
    pass = context.getInitParameter("pass");
}

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    String recipient = request.getParameter("To"); // this i will get from login query
    String subject = request.getParameter("subject");//this i can define manually
    String content = request.getParameter("content");//same for this also


    String resultMessage = "";

    try {
        EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
                content);
        resultMessage = "The e-mail was sent successfully";
    } catch (Exception ex) {
        ex.printStackTrace();
        resultMessage = "There were an error: " + ex.getMessage();
    } 
}

}

Java Utility classs

public class EmailUtility {
public static void sendEmail(String host, String port, final String userName, final String password,
        String toAddress, String subject, String message) throws AddressException, MessagingException {


    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    });
    session.setDebug(false);
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(userName));
    if (toAddress!= null) {
        List<String> emails = new ArrayList<>();
        if (toAddress.contains(",")) {
            emails.addAll(Arrays.asList(toAddress.split(",")));
        } else {
            emails.add(toAddress);
        }
        Address[] to = new Address[emails.size()];
        int counter = 0;
        for(String email : emails) {
            to[counter] = new InternetAddress(email.trim());
            counter++;
        }
        msg.setRecipients(Message.RecipientType.TO, to);
    }
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    msg.setText(message);

    Transport.send(msg);

}

}

Eugène Adell
  • 2,644
  • 2
  • 14
  • 30
  • You have to write a cron expression for a particular time and create scheduler to send email. – Sambit May 14 '19 at 06:32
  • https://stackoverflow.com/q/19573457/2970947 – Elliott Frisch May 14 '19 at 06:34
  • @Sambit cron? i don't know about this –  May 14 '19 at 06:35
  • @ElliottFrisch `quartz` i don't know what it is and i am using simple java and servlets not any kind of framework –  May 14 '19 at 06:37
  • You can learn about cron expressions and you have to learn quartz also about how to use in java. Check this link. https://www.baeldung.com/cron-expressions – Sambit May 14 '19 at 06:40
  • @Sambit is there any simple way to do this as what i have done till now because i am totally new to this –  May 14 '19 at 06:42
  • Have you looked at this example or similar https://www.java4s.com/core-java/send-java-email-in-specific-time-interval-automatically-dynamically/ Also, https://stackoverflow.com/questions/12421288/how-to-send-email-automatically-at-particular-time-of-day-in-java – Sohan May 14 '19 at 06:43

3 Answers3

0

In java the scheduler is used to schedule a thread or task that executes at a certain period of time or periodically at a fixed interval. There are multiple ways to schedule a task in Java :

  • java.util.TimerTask
  • java.util.concurrent.ScheduledExecutorService
  • Quartz Scheduler
  • org.springframework.scheduling.TaskScheduler

For pure java implementation without any framework usage, using ScheduledExecutorService running a task at certain periods:

public void givenUsingExecutorService_whenSchedulingRepeatedTask_thenCorrect() 
  throws InterruptedException {
    TimerTask repeatedTask = new TimerTask() {
        public void run() {
        EmailUtility.sendEmail(host, port, user, pass, recipient,object,content);
        System.out.println("The e-mail was sent successfully");
    }
};

ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
ZonedDateTime nextRun = now.withHour(5).withMinute(0).withSecond(0);
if(now.compareTo(nextRun) > 0)
  nextRun = nextRun.plusDays(1);
Duration duration = Duration.between(now, nextRun);
long initalDelay = duration.getSeconds();

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(repeatedTask,
initalDelay,
TimeUnit.DAYS.toSeconds(1),
TimeUnit.SECONDS);
executor.shutdown();
}
Ananthapadmanabhan
  • 4,089
  • 5
  • 17
  • 31
  • 1
    I am not using spring i am using simple java and servlets, so with this how can i achieve this –  May 14 '19 at 06:38
  • 1
    Okay , In that case https://stackoverflow.com/questions/7814089/how-to-schedule-a-periodic-task-in-java – Ananthapadmanabhan May 14 '19 at 06:43
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/193309/discussion-between-dheeraj-kumar-and-ananthapadmanabhan). –  May 14 '19 at 07:32
0

You can use a ScheduledExecutorService for handling this in "plain" Java:

 ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
 int count = 0;

        Runnable task = () -> {
            count++;
            System.out.println(count);
        };

        ScheduledFuture<?> scheduledFuture = ses.scheduleAtFixedRate(task, 12, TimeUnit.HOURS);

There is also a method for using an initial delay, but you can read more here: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

For your use case:

Introduce a new class EmailSendJobUtil:

public class EmailSendUtil {
  public void createAndSubmitSheduledJob() {
   ScheduledExecutorService ses = Executors.sheduledThreadPool(1);
   ScheduledFuture<> sheduledFuture = ses.sheduleAtFixedRate(EmailUtility.sendMail(), 12, TimeUnit.HOURS);
  }
}

However, you will get troubles with your code structure. Try to introduce a method in your EmailUtility that encapsulates the automatated sending of mails.

Introduce a repository for saving to which users you have to send mails automatically and read this data in the new method that only handles the automatic sending. You could do something like this:

public class MailJobRepository {
  private List<MailJob> jobs;

  void add();
  void remove();
  List<> getJobs();
}

And in your EmailUtility introduce a new method:

public void sendAutomatedEmails() {
  jobRepository.getJobs().foreach(job -> {
   sendMail(job.getToAddress(), job.getSubject(), job.getMessage());
  });
}

Then you can shedule this new method and you have splitted your code into logical seperate parts.

Just a little hint:

String host, String port, final String userName, final String password  

This is data for your "side" of the email sending and should not be passed as a method parameter. You can save this data into your EmailUtility class.

ItFreak
  • 1,986
  • 4
  • 17
  • 36
  • hey here `task, 12, TimeUnit.HOURS);` in this line 12 is hour? where should i write in my code should i create new class or in my `utility` class? –  May 14 '19 at 06:51
  • no i don't want to send it at time interval as you are saying each 12 hours i want to send it when time is at midnight that is 24:00 when ever the Apache server starts that doesn't matter i jsut want to send the mail when it is 24:00 i.e mid night or after midnight at 1-2 –  May 14 '19 at 07:11
  • what did `MailJobRepository` class do is it a bean class? –  May 14 '19 at 07:15
  • I introduced that class to separate your data holding from your working code. I think you should start learning software development techniques and java basics first... – ItFreak May 14 '19 at 07:18
  • actually i am working on `UI` but this is the new task to do in java and i have only some basic knowledge in java that is why facing this kind of issues –  May 14 '19 at 07:32
0

You should take a look to isocline's Clockwork it's a java process engine. It is capable of coding various functions more efficiently than Quartz, and has specific execution function.