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);
}
}