Newsletter

Send Java EMail in Specific Time Interval Automatically & Dynamically

Core Java » on Oct 7, 2012 { 27 Comments } By Sivateja

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.

Directory Structure

GMailServer.java

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

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

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

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

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

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…..

 

Output

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

27 Responses to “Send Java EMail in Specific Time Interval Automatically & Dynamically”
  1. hi frnd,this is really awesome tutorial for java developers ,actuallly when iam trying to execute this example im getting error follws….

    Email Sent Succesfully…
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    class javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
    nested exception is:
    java.net.UnknownHostException: smtp.gmail.com
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at JAVAEmail.GMailServer.sendMail(GMailServer.java:61)
    at JAVAEmail.Testing.run(Testing.java:15)
    at java.util.TimerThread.mainLoop(Unknown Source)
    at java.util.TimerThread.run(Unknown Source)

    error….plz help in execution by sending an email to my mail id ,
    thanks in advance

  2. ram says:

    Hi frnd
    I also practiced wit this code its really helpful ,Thanks

  3. neha says:

    sir from where i can download BarCode128Java4s.java file….please give me the respective link..

  4. Jinshad says:

    Gud job….. Thanks a lot….

  5. Hareesh says:

    I am getting the following error plse help to slove this

    Scheduler Starterd…

    Exception in thread “Timer-0” java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
    at javax.mail.Session.loadProvidersFromStream(Session.java:928)
    at javax.mail.Session.access$000(Session.java:174)
    at javax.mail.Session$1.load(Session.java:870)
    at javax.mail.Session.loadResource(Session.java:1084)
    at javax.mail.Session.loadProviders(Session.java:889)
    at javax.mail.Session.(Session.java:210)
    at javax.mail.Session.getDefaultInstance(Session.java:299)
    at emial.GMailServer.(GMailServer.java:41)
    at emial.Testing.run(Testing.java:12)
    at java.util.TimerThread.mainLoop(Timer.java:512)
    at java.util.TimerThread.run(Timer.java:462)

  6. developer says:

    Is it recommended to use “Timer” in Java EE web applications?

  7. Saleen Conzalo says:

    I am getting the following error plse help to slove this

    Scheduler Starterd…
    javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and then try again.
    534-5.7.14 Learn more at
    534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 mi8sm21900010pdb.91 – gsmtp

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:648)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:583)
    at javax.mail.Service.connect(Service.java:313)
    at javax.mail.Service.connect(Service.java:172)
    at javax.mail.Service.connect(Service.java:121)
    at javax.mail.Transport.send0(Transport.java:190)
    at javax.mail.Transport.send(Transport.java:120)
    at java4s.GMailServer.sendMail(GMailServer.java:60)
    at java4s.Testing.run(Testing.java:15)
    at java.util.TimerThread.mainLoop(Unknown Source)
    at java.util.TimerThread.run(Unknown Source)
    Email Sent Succesfully…

  8. vani says:

    Hi i tried this example,

    But its showing compile time error near scheduleAtFixedRate , (Suggestion is The method scheduleAtFixedRate(TimerTask, long, long) in the type Timer is not applicable for the arguments (Testing, long, long)) please suggest me on this…

  9. Neha says:

    I want to integrate this scheduler to my project. i need to check first that does the costumer has given his feedback, if not then after 20 days i want to send a reminder to saying “give feedback”. how can i do that my project is on java using jsp & servlets.
    Please help asap.

    thanks in advance 🙂

  10. siva says:

    Scheduler Starterd…
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    class javax.mail.AuthenticationFailedException
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at java4s.GMailServer.sendMail(GMailServer.java:62)
    at java4s.Testing.run(Testing.java:16)
    at java.util.TimerThread.mainLoop(Timer.java:512)
    at java.util.TimerThread.run(Timer.java:462)
    exception….plz help in execution by sending an email to my mail id ,
    thanks in advance

  11. rehan says:

    Email Sent Succesfully…
    at javax.mail.internet.InternetAddress.checkAddress(InternetAddress.java:926)
    at javax.mail.internet.InternetAddress.parse(InternetAddress.java:819)
    at javax.mail.internet.InternetAddress.parse(InternetAddress.java:555)
    at javax.mail.internet.InternetAddress.(InternetAddress.java:91)
    at java4s.GMailServer.sendMail(GMailServer.java:52)
    at java4s.Testing.run(Testing.java:15)
    at java.util.TimerThread.mainLoop(Unknown Source)
    at java.util.TimerThread.run(Unknown Source)
    javax.mail.internet.AddressException: Illegal whitespace in address in string “your from email id”
    Email Sent Succesfully…
    at javax.mail.internet.InternetAddress.checkAddress(InternetAddress.java:926)
    at javax.mail.internet.InternetAddress.parse(InternetAddress.java:819)
    at javax.mail.internet.InternetAddress.parse(

  12. komal says:

    java4s is really worth it.

    For email sending program i m getting this exception
    Scheduler Starterd…
    Email Sent Succesfully…
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    class javax.mail.AuthenticationFailedException
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at javafiles.GMailServer.sendMail(GMailServer.java:60)
    at javafiles.Testing.run(Testing.java:14)
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505)
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    class javax.mail.AuthenticationFailedException
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at javafiles.GMailServer.sendMail(GMailServer.java:60)
    at javafiles.Testing.run(Testing.java:14)
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505)
    Email Sent Succesfully…

    pls send solution to mail id

  13. Komal says:

    Hi,
    I tried this example.But i am getting this exception as follows
    Scheduler Starterd…
    Email Sent Succesfully…
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    class javax.mail.AuthenticationFailedException
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at javafiles.GMailServer.sendMail(GMailServer.java:60)
    at javafiles.Testing.run(Testing.java:14)
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505)
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    class javax.mail.AuthenticationFailedException
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at javafiles.GMailServer.sendMail(GMailServer.java:60)
    at javafiles.Testing.run(Testing.java:14)
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505)
    Email Sent Succesfully…
    pls help me out..
    thnx 🙂

  14. Aishwarya says:

    The code works great. Mail is sent to the Email ID specified. In the notification and the Inbox Sender mail is not shown. In the notification and No Sender Mail Id in the Inbox. Please provide a solution

  15. kalyani says:

    HI,FRIENDS I GOT THIS ERROR.PLEASE HELP.

    javax.mail.internet.AddressException: Illegal whitespace in address in string “your from email id”
    Email Sent Succesfully… at javax.mail.internet.InternetAddress.checkAddress(InternetAddress.java:900)
    at javax.mail.internet.InternetAddress.parse(InternetAddress.java:793)
    at javax.mail.internet.InternetAddress.parse(InternetAddress.java:529)
    at javax.mail.internet.InternetAddress.(InternetAddress.java:65)
    at java4s.GmailServer.sendMail(GmailServer.java:52)
    at java4s.Testing.run(Testing.java:14)
    at java.util.TimerThread.mainLoop(Unknown Source)
    at java.util.TimerThread.run(Unknown Source)

    javax.mail.internet.AddressException: Illegal whitespace in address in string “your from email id”
    Email Sent Succesfully…
    at javax.mail.internet.InternetAddress.checkAddress(InternetAddress.java:900)
    at javax.mail.internet.InternetAddress.parse(InternetAddress.java:793)
    at javax.mail.internet.InternetAddress.parse(InternetAddress.java:529)
    at javax.mail.internet.InternetAddress.(InternetAddress.java:65)
    at java4s.GmailServer.sendMail(GmailServer.java:52)
    at java4s.Testing.run(Testing.java:14)
    at java.util.TimerThread.mainLoop(Unknown Source)
    at java.util.TimerThread.run(Unknown Source)

  16. Mohd Islam says:

    Hi Java4s guys
    Really you guys provide the best online tutorials……
    We users are really thankfull to all of your teams

    The above codes throws some exceptions that are as follows

    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    class javax.mail.AuthenticationFailedException

    Please provide me solution. I have tried it all the ways but didnt get any solution

  17. arvind says:

    thanks,this is very good example and it is working.My problem is that execute query everyday on a specific time period and result is automatically attached it as a attachment and mail to other mail id .how to make it possible please reply me.I am very thankful to all…..

    • Vinod says:

      Hlo boss my code is not working I have got some error please tell me solution for me

      javax.mail.internet.AddressException: Illegal whitespace in address in string “your from email id”
      Email Sent Succesfully… at javax.mail.internet.InternetAddress.checkAddress(InternetAddress.java:900)
      at javax.mail.internet.InternetAddress.parse(InternetAddress.java:793)
      at javax.mail.internet.InternetAddress.parse(InternetAddress.java:529)
      at javax.mail.internet.InternetAddress.(InternetAddress.java:65)
      at java4s.GmailServer.sendMail(GmailServer.java:52)
      at java4s.Testing.run(Testing.java:14)
      at java.util.TimerThread.mainLoop(Unknown Source)
      at java.util.TimerThread.run(Unknown Source)

      javax.mail.internet.AddressException: Illegal whitespace in address in string “your from email id”
      Email Sent Succesfully…
      at javax.mail.internet.InternetAddress.checkAddress(InternetAddress.java:900)
      at javax.mail.internet.InternetAddress.parse(InternetAddress.java:793)
      at javax.mail.internet.InternetAddress.parse(InternetAddress.java:529)
      at javax.mail.internet.InternetAddress.(InternetAddress.java:65)
      at java4s.GmailServer.sendMail(GmailServer.java:52)
      at java4s.Testing.run(Testing.java:14)
      at java.util.TimerThread.mainLoop(Unknown Source)
      at java.util.TimerThread.run(Unknown Source)

  18. Birendra Kumar Verma says:

    The code works great. Mail is sent to the Email ID specified.

  19. Uday says:

    its worked great

  20. Sneha says:

    Sir,

    How to include that .properties file to the JAR File?

  21. Shruthi Jayakumar says:

    Sir, I am getting error in ReadPropertiesFile may i know why?

  22. pavithra says:

    mail.jar
    activation.jar
    commons-email-1.0.jar

    How to import above jars please explain

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.