How to send Email in Specific time interval continously Using Timer
FreeMarker is a "template engine"; a generic tool to generate text output (anything from HTML to autogenerated source code) based on templates. It's a Java package, a class library for Java programmers. It's not an application for end-users in itself, but something that programmers can embed into their products.
reference(http://freemarker.sourceforge.net/)
I am using freemarker template for creating the email body. I have used my gmail a/c username and password for the email send test purpose. So if you want to execute your program then in the Constant.java file use your gmail username and password for FROM_MAIL_ID and FROM_MAIL_ID_PASS property.
Before going through the below program few jars are required, the references are given below:-
1) http://www.java2s.com/Code/Jar/a/Downloadactivationjar.htm - activation.jar
2) mirrors.ibiblio.org/pub/mirrors/maven2/freemarker/freemarker/2.3.4/freemarker-2.3.4.jar - freemarker.jar
3) http://www.java2s.com/Code/Jar/m/Downloadmailjar.htm - mail.jar
STEP - 1
1) Create java file and name it as Constants.java file as below:-
package com.gaurav.examples.mail;
public class Constants
{
public static final String TEMPLATE_FILENAME = "html-mail-template.ftl";
public static final String ATTACHMENT_FILENAME = "welcome.txt";
public static final String MAIL_SEND_SUCCESS_STATUS = "mail Sent successfully";
public static final String MAIL_SEND_SUCCESS_FAIL = "mail send failed";
public static final String FROM_MAIL_ID = "test@gmail.com";//This is From mail-id.
public static final String FROM_MAIL_ID_PASS ="Please keep ur password here";//From Mail-id password.
public static final String TO_MAIL_ID = "tomailIdUsername@gmail.com";//Please use to mail id here.
public static final String MAIL_SUBJECT = "Sending a Test mail through Java Mail API";
public static final String TO_MAIL = "to";
public static final String TO_MAIL_NAME = "Gollu";
public static final String MAIL_BODY = "body";
public static final String EMAIL_BODY_CONTENT = "See the text file and reply the answer?";
public static final String FROM_MAIL = "from";
public static final String FROM_MAIL_NAME = "Kumar.";
public static final String PROPERTY_FILENAME ="settings.properties";
public static final String BODY_CONTENT_TYPE="text/html";
}
public class Constants
{
public static final String TEMPLATE_FILENAME = "html-mail-template.ftl";
public static final String ATTACHMENT_FILENAME = "welcome.txt";
public static final String MAIL_SEND_SUCCESS_STATUS = "mail Sent successfully";
public static final String MAIL_SEND_SUCCESS_FAIL = "mail send failed";
public static final String FROM_MAIL_ID = "test@gmail.com";//This is From mail-id.
public static final String FROM_MAIL_ID_PASS ="Please keep ur password here";//From Mail-id password.
public static final String TO_MAIL_ID = "tomailIdUsername@gmail.com";//Please use to mail id here.
public static final String MAIL_SUBJECT = "Sending a Test mail through Java Mail API";
public static final String TO_MAIL = "to";
public static final String TO_MAIL_NAME = "Gollu";
public static final String MAIL_BODY = "body";
public static final String EMAIL_BODY_CONTENT = "See the text file and reply the answer?";
public static final String FROM_MAIL = "from";
public static final String FROM_MAIL_NAME = "Kumar.";
public static final String PROPERTY_FILENAME ="settings.properties";
public static final String BODY_CONTENT_TYPE="text/html";
}
STEP - 2
1) Create a java file and name it as SendMail.java, use the below contents
package com.gaurav.examples.mail;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class SendMail {
private String strMailSendStatus = null;
public String mailSend() throws Exception {
Properties props = new Properties();
try {
props.load(new FileInputStream(
new File(Constants.PROPERTY_FILENAME)));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Session session = Session.getDefaultInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
Constants.FROM_MAIL_ID,
Constants.FROM_MAIL_ID_PASS);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress());
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(Constants.TO_MAIL_ID));
message.setSubject(Constants.MAIL_SUBJECT);
BodyPart body = new MimeBodyPart();
// freemarker api use for using it's template.
Configuration cfg = new Configuration();
Template template = cfg.getTemplate(Constants.TEMPLATE_FILENAME);
Map<String, String> rootMap = new HashMap<String, String>();
rootMap.put(Constants.TO_MAIL, Constants.TO_MAIL_NAME);
rootMap.put(Constants.MAIL_BODY, Constants.EMAIL_BODY_CONTENT);
rootMap.put(Constants.FROM_MAIL, Constants.FROM_MAIL_NAME);
Writer out = new StringWriter();
template.process(rootMap, out);
// freemarker api use for using it's template ends here.
/* we can keep html tags in our text for the decoration purpose. */
body.setContent(out.toString(), "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
body = new MimeBodyPart();
String filename = Constants.ATTACHMENT_FILENAME;
DataSource source = new FileDataSource(filename);
body.setDataHandler(new DataHandler(source));
body.setFileName(filename);
multipart.addBodyPart(body);
message.setContent(multipart, "text/html");
Transport.send(message);
strMailSendStatus = Constants.MAIL_SEND_SUCCESS_STATUS;
} catch (MessagingException e) {
e.printStackTrace();
strMailSendStatus = Constants.MAIL_SEND_SUCCESS_FAIL;
}
return strMailSendStatus;
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class SendMail {
private String strMailSendStatus = null;
public String mailSend() throws Exception {
Properties props = new Properties();
try {
props.load(new FileInputStream(
new File(Constants.PROPERTY_FILENAME)));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Session session = Session.getDefaultInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
Constants.FROM_MAIL_ID,
Constants.FROM_MAIL_ID_PASS);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress());
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(Constants.TO_MAIL_ID));
message.setSubject(Constants.MAIL_SUBJECT);
BodyPart body = new MimeBodyPart();
// freemarker api use for using it's template.
Configuration cfg = new Configuration();
Template template = cfg.getTemplate(Constants.TEMPLATE_FILENAME);
Map<String, String> rootMap = new HashMap<String, String>();
rootMap.put(Constants.TO_MAIL, Constants.TO_MAIL_NAME);
rootMap.put(Constants.MAIL_BODY, Constants.EMAIL_BODY_CONTENT);
rootMap.put(Constants.FROM_MAIL, Constants.FROM_MAIL_NAME);
Writer out = new StringWriter();
template.process(rootMap, out);
// freemarker api use for using it's template ends here.
/* we can keep html tags in our text for the decoration purpose. */
body.setContent(out.toString(), "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
body = new MimeBodyPart();
String filename = Constants.ATTACHMENT_FILENAME;
DataSource source = new FileDataSource(filename);
body.setDataHandler(new DataHandler(source));
body.setFileName(filename);
multipart.addBodyPart(body);
message.setContent(multipart, "text/html");
Transport.send(message);
strMailSendStatus = Constants.MAIL_SEND_SUCCESS_STATUS;
} catch (MessagingException e) {
e.printStackTrace();
strMailSendStatus = Constants.MAIL_SEND_SUCCESS_FAIL;
}
return strMailSendStatus;
}
}
STEP - 3
1) Create a java file and name it as SendMailCaller.java as below
package com.gaurav.examples.mail;
import java.util.TimerTask;
public class SendMailCaller extends TimerTask
{
public void run()
{
SendMail sender = new SendMail();
String mailSendStatus = null;
try{
mailSendStatus = sender.mailSend();
}catch(Exception e){
e.printStackTrace();
}
System.out.println("Email Sent status ->"+mailSendStatus);
}
}
import java.util.TimerTask;
public class SendMailCaller extends TimerTask
{
public void run()
{
SendMail sender = new SendMail();
String mailSendStatus = null;
try{
mailSendStatus = sender.mailSend();
}catch(Exception e){
e.printStackTrace();
}
System.out.println("Email Sent status ->"+mailSendStatus);
}
}
STEP - 4
1) Create a java file and name it as EmailJobScheduler.java like below:-
package com.gaurav.examples.mail;
import java.util.Timer;
public class EmailJobScheduler {
public void callScheduler() throws Exception {
System.out.println("Scheduler Starterd...");
Timer timer = new Timer();
timer.scheduleAtFixedRate(new SendMailCaller(), getTimeDelayAndPeriod("2s"),
getTimeDelayAndPeriod("10s"));
}
public long getTimeDelayAndPeriod(String value) throws Exception {
long l = 0;
String val = "";
try {
if (value.endsWith("d") || value.endsWith("D")) {
val = value.substring(0, value.length() - 1);
l = Long.parseLong(val) * 24 * 60 * 60 * 1000;
}
else if (value.endsWith("h") || value.endsWith("H")) {
val = value.substring(0, value.length() - 1);
l = Long.parseLong(val) * 60 * 60 * 1000;
} else if (value.endsWith("m") || value.endsWith("M")) {
val = value.substring(0, value.length() - 1);
l = Long.parseLong(val) * 60 * 1000;
} else if (value.endsWith("s") || value.endsWith("S")) {
val = value.substring(0, value.length() - 1);
l = Long.parseLong(val) * 1000;
} else {
l = Long.parseLong(value);
}
} catch (Exception e) {
throw new Exception(e);
}
return l;
}
public static void main(String a[]) throws Exception {
EmailJobScheduler emailJobScheduler = new EmailJobScheduler();
emailJobScheduler.callScheduler();
}
}
import java.util.Timer;
public class EmailJobScheduler {
public void callScheduler() throws Exception {
System.out.println("Scheduler Starterd...");
Timer timer = new Timer();
timer.scheduleAtFixedRate(new SendMailCaller(), getTimeDelayAndPeriod("2s"),
getTimeDelayAndPeriod("10s"));
}
public long getTimeDelayAndPeriod(String value) throws Exception {
long l = 0;
String val = "";
try {
if (value.endsWith("d") || value.endsWith("D")) {
val = value.substring(0, value.length() - 1);
l = Long.parseLong(val) * 24 * 60 * 60 * 1000;
}
else if (value.endsWith("h") || value.endsWith("H")) {
val = value.substring(0, value.length() - 1);
l = Long.parseLong(val) * 60 * 60 * 1000;
} else if (value.endsWith("m") || value.endsWith("M")) {
val = value.substring(0, value.length() - 1);
l = Long.parseLong(val) * 60 * 1000;
} else if (value.endsWith("s") || value.endsWith("S")) {
val = value.substring(0, value.length() - 1);
l = Long.parseLong(val) * 1000;
} else {
l = Long.parseLong(value);
}
} catch (Exception e) {
throw new Exception(e);
}
return l;
}
public static void main(String a[]) throws Exception {
EmailJobScheduler emailJobScheduler = new EmailJobScheduler();
emailJobScheduler.callScheduler();
}
}
STEP - 5
1) Create a file and name it as html-mail-template.ftl, use the below contents:-
<html>
<body>
Hi ${to},
<p style='color:midnightblue;'>${body}</p>
Regards,<br/>
${from}.
</body>
</html>
<body>
Hi ${to},
<p style='color:midnightblue;'>${body}</p>
Regards,<br/>
${from}.
</body>
</html>
STEP - 6
1) Create a text file and name it as welcome.txt, use the below content:-
Who is elected as the president of India in 2012?
STEP - 7
1) Create a file and name it as settings.properties, and use the below content:
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.auth=truemail.smtp.port=465
mail.smtp.host=smtp.gmail.com
mail.smtp.socketFactory.port=465
STEP - 8
In order to run this application three external jars are required which is as below:-
Required Jars - (download link)
activation.jar - http://www.java2s.com/Code/Jar/a/Downloadactivationjar.htm
freemarker.jar - http://www.java2s.com/Code/Jar/f/Downloadfreemarker2316jar.htm
References are given above.
The project directory structure is given below:-
No comments:
Post a Comment