Pages

Tuesday, 10 September 2013

Send Java EMail in Specific Time Interval Automatically & Dynamically



Let us see how to send automatic and dynamic email using Java, this application will send email in fixed interval of time, even if you want you can change this application to send email every day at particular time :-), to wish your friends/family.



GMailServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package java4s;
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");
        }
    }
}
DBScheduler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package java4s;
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();
        }

    }
ReadPropertiesFile.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package java4s;

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")+"/java4s_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);
        }

    }

}
Testing.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package java4s;

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 Java4s",Constants.setFrom,Constants.emailTO);
            }
                   catch (Exception e) {
                 e.printStackTrace();
            }  

                System.out.println("Email Sent Succesfully...");

            }
}
Constants.java
1
2
3
4
5
6
7
8
9
10
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;
}
java4s_Props.properties
1
2
3
4
5
6
7
8
9
10
setFrom = your from email id
setPassword = your password

#repeat for every 10 seconds
timetoquery = 10s

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

emailTO = your to email id
Explanation
  • Run DBScheduler.java to start this application
  • First time email will sent after 2 seconds and repeats every 10 seconds until you stop your application
  • Just change .properties file and change what ever you want, you no need to touch any .java files :-)
  • You no need to touch GMailServer.java
Jars Required
  • mail.jar
  • activation.jar
  • commons-email-1.0.jar
Download these jars…..

No comments:

Post a Comment