Java Code to Send an Email With Time Scheduling

Image

Java Code To  Send a Mail  With   a Time Intervals

5 steps u have to Fallow

1.Create a GMailServer.java

package com.java.mail;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class GMailServer extends javax.mail.Authenticator
{
private String mailhost =”smtp.gmail.com”; ; //”smtp.mail.yahoo.com”; //”smtp.gmail.com”;
private String user;
private String password;
private Session session;

public GMailServer(String user, String password) {
this.user = user;
this.password = password;

Properties props = new Properties();
props.setProperty(“mail.transport.protocol”, “smtp”);
props.setProperty(“mail.smtp.host”, mailhost);
props.put(“mail.smtp.auth”, “true”);
props.put(“mail.smtp.port”, “465”);
props.put(“mail.smtp.socketFactory.port”, “465”);
props.put(“mail.smtp.socketFactory.class”,”javax.net.ssl.SSLSocketFactory”);
props.put(“mail.smtp.starttls.enable”,”true”);
props.put(“mail.smtp.debug”, “true”);
props.put(“mail.smtp.socketFactory.fallback”, “false”);
props.setProperty(“mail.smtp.quitwait”, “false”);

session = Session.getDefaultInstance(props, this);
}

protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, password);
}

public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception
{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), “text/plain”));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(‘,’) > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}

public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;

public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}

public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}

public void setType(String type) {
this.type = type;
}

public String getContentType() {
if (type == null)
return “application/octet-stream”;
else
return type;
}

public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}

public String getName() {
return “ByteArrayDataSource”;
}

public OutputStream getOutputStream() throws IOException {
throw new IOException(“Not Supported”);
}
}
}

                                            2. Create DBScheduler.java

package com.java.mail;

import java.util.Timer;
import JavaConstants.Constants;

public class DBScheduler
{

public void callScheduler() throws Exception
{

System.out.println(“Scheduler Starterd…”);
ReadPropertiesFile.readConfig();
Timer timer = new Timer();

timer.scheduleAtFixedRate(new Testing(), getTimePrecision(Constants.delay), getTimePrecision(Constants.timetoquery));

}

public long getTimePrecision(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
{
DBScheduler dbs = new DBScheduler();
dbs.callScheduler();
}

}

3.Create Testing.java

package com.java.mail;
import java.util.TimerTask;
import JavaConstants.Constants;

public class Testing extends TimerTask
{

public void run()
{
GMailServer sender = new GMailServer(Constants.setFrom, Constants.setPassword);
try {
sender.sendMail(“Subject”,”This is RAJ”,Constants.setFrom,Constants.emailTO);
}
catch (Exception e) {
e.printStackTrace();
}

System.out.println(“Email Sent Succesfully…”);

}
}

                                        4.Create ReadPropertiesFile.java

package com.java.mail;
import java.io.FileInputStream;
import java.util.Properties;
import JavaConstants.Constants;

public class ReadPropertiesFile
{
public  static void readConfig() throws Exception
{
try
{

Properties pro = new Properties();
String path = System.getProperty(“user.dir”)+”/java_Props.properties”;
pro.load(new FileInputStream(path));
Constants.delay = pro.getProperty(“delay”);
Constants.timetoquery = pro.getProperty(“timetoquery”);
Constants.setFrom = pro.getProperty(“setFrom”);
Constants.setPassword = pro.getProperty(“setPassword”);
Constants.emailTO = pro.getProperty(“emailTO”);

}
catch(Exception e)
{
throw new Exception(e);
}

}

}

                                  5. Create  Constant.java in another package

package JavaConstants;

public class Constants
{
public static String delay;
public static String timetoquery;
public static String setFrom;
public static String setPassword;
public static String emailTO;
}

6.Configuration File is here Just Named it as java_props.properties

setFrom = abc@gmail.com
setPassword = XXXXXXX

#repeat for every 10 seconds
timetoquery = 1h

#start after 2seconds for first time..
delay = 2s

emailTO = reciever@gmail.com

At last add these Three jar files into ur project

  activation.jar,common-email.jar,mail.jar

Note: Never Disturb GMailServer.java  Run only DbScheduler.java

While Executing this project u can send a Mails With time Span How Ever U like

I hope u Understand the scenario Very Well any Doudbts are else any clarifications just send Me feed Back…………….

With Regard’s

K.RAJA SEKHAR REDDY(RAJ9992)
Software Engineer

Advertisements
This entry was posted in Java Codes Examples and tagged . Bookmark the permalink.

One Response to Java Code to Send an Email With Time Scheduling

  1. Pingback: Java program checks the authenticity of the email | Eng / Mohammed Samir

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s