Tuesday, February 15, 2011

Send Mail in specific time Interval using Java

The following jar files required to send mail using java program.
1)Activation.jar
2)Mail.jar
Click this Link to download the jar file.
Okay you have downloaded the jar files and placed the same in classpath.

Lets discuss the program step by step.
There are two options mentioned in this program.Single and multiple
While running program it will ask input from the user single or multiple.
If the user gives single as input the mail will send only once.The program get executes after the timedelay specified in the program.Here we specified as 1000milliseconds.

If the user pass multiple as input then the program send the mail multiple times with time interval as 10000milliseconds
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

public class sendMailUsingTimeInterval{
 public static void main(String[] args) throws IOException{
     int delayInMilliSec= 1000; //in milli seconds.
     int delayBetweenExec = 10000;//in milli seconds
     Timer timer = new Timer();
     System.out.println("Please enter \'Single\' or \'Multiple\')?");
     BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
     String ans = in.readLine();
     if (ans.equalsIgnoreCase("Single")){
       timer.schedule(new TimerTask(){     
         public void run(){
          SendMailUsingAuthentication send = new SendMailUsingAuthentication();
          try {
     send.sendingDetails();
    } catch (Exception e) {
     System.out.println("in catch block:::");
     e.printStackTrace();
    }
          System.out.println("Single time selected ***");
         }
       },delayInMilliSec);
     }
     else if(ans.equalsIgnoreCase("Multiple")){
       timer.schedule(new TimerTask(){
         public void run(){
          SendMailUsingAuthentication send = new SendMailUsingAuthentication();
          try {
     send.sendingDetails();
    } catch (Exception e) {
     System.out.println("in catch block:::");
     e.printStackTrace();
    }
           System.out.println("Multiple time selected ****");
         }
       },delayInMilliSec,delayBetweenExec);
     }
     else{
      System.out.println("Pass single or multiple as input ***");
      System.exit(0);
     }
   }
}
In above program you can see the method sendingDetails get called.
The sendingDetails method contain the information about the host,port,from user,to user and content.Make sure your local machine machine has internet facility then give host as localhost else give the ip address of the machine.
Generally the port number is 25.
Then you know the from address,to mail address and the mail content also.
pass all the information.
sendingDetails method now invoke the mailSending() method in the same program.
In mailSending method set all valuse to message.
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailUsingAuthentication {
  
    public void mailSending(String smtpHost, int smtp_Port,
                            String from, String to,
                            String subject, String content)
                throws AddressException, MessagingException {

        // Create a mail session
     java.util.Properties props = new java.util.Properties();
     
     String smtpPort = Integer.toString(smtp_Port);
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);
        props.put("mail.smtp.auth", "true");
        
        Session session = Session.getDefaultInstance(props, null);
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));//set from mailId here.
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));//set to mailId here.
        msg.setRecipient(Message.RecipientType.CC,new InternetAddress(to));//set cc mailId here.
        msg.setSubject(subject);//mail Subject
        msg.setContent(content,"text/plain");//mail content in plain format
        /*
         * To send mail in HTML format disable the 
         * above content and enable the below one
         */

//      msg.setContent("

HTML TYPE MESSAGE

","text/html");//mail Type.It may be plain or html whatever. /* * In below I have set the mail sent date as previous date. * Default it set present date as sent date. * you can change this as your wish. * If you want to enable for previous date.just uncomment the below code */ /*Calendar origDay = Calendar.getInstance(); System.out.println ("Original Date: " + origDay.getTime()); Calendar prevDay = (Calendar) origDay.clone(); prevDay.add (Calendar.DAY_OF_YEAR, -1); DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); msg.setSentDate(prevDay.getTime());*/ String mailHost= "urmail.host.com";//mailHost for your mail provider.For gmail smtp.gmail.com String userName = "from";//userName for an E-mail provider. String password = "password";//password for the same. Transport tr = session.getTransport("smtp"); tr.connect(mailHost,userName,password); System.out.println("whether connection established***"+tr.isConnected()); msg.saveChanges(); tr.sendMessage(msg, msg.getAllRecipients()); tr.close(); System.out.println("Message sent OK."); } public void sendingDetails() throws Exception { mailSending("localhost", 25, "from@gmail.com", "to@gmail.com", "Sriram", "Test mail."+"\n"+"\n"+"Cheers,"+"\n"+"Sriram.V"); } }
Read the comments in the program for more clarification.
Here we send the mail by using Transport.
Transport opens the connection and it connects to mail host.
After the Connection open we are going to send mail using tr.sendMessage()
Once the mail has been successfully send the connection is get closed by calling tr.close()

Possible execptions
AuthenticationFailedException:
Check the user name and password given in the program to connect to the Transport.
javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:306)
at javax.mail.Service.connect(Service.java:156)
at sriram.tutorial.javapgm.SendMailUsingAuthentication.mailSending(SendMailUsingAuthentication.java:61)
at sriram.tutorial.javapgm.SendMailUsingAuthentication.sendingDetails(SendMailUsingAuthentication.java:70)
at sriram.tutorial.javapgm.sendMailUsingTimeInterval$1.run(example.java:25)
at java.util.TimerThread.mainLoop(Timer.java:432)
at java.util.TimerThread.run(Timer.java:382)
MessagingException:
Check the mailHost.It attempt to connect to the given host but failed to connet.
javax.mail.MessagingException: Exception reading response;
  nested exception is:
 java.net.SocketException: Connection reset
 at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1462)
 at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1260)
 at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
 at javax.mail.Service.connect(Service.java:275)
 at javax.mail.Service.connect(Service.java:156)
 at sriram.tutorial.javapgm.SendMailUsingAuthentication.mailSending(SendMailUsingAuthentication.java:61)
 at sriram.tutorial.javapgm.SendMailUsingAuthentication.sendingDetails(SendMailUsingAuthentication.java:70)
 at sriram.tutorial.javapgm.sendMailUsingTimeInterval$1.run(example.java:25)
 at java.util.TimerThread.mainLoop(Timer.java:432)
 at java.util.TimerThread.run(Timer.java:382)
Caused by: java.net.SocketException: Connection reset
 at java.net.SocketInputStream.read(SocketInputStream.java:168)
 at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:97)
 at java.io.BufferedInputStream.fill(BufferedInputStream.java:183)
 at java.io.BufferedInputStream.read(BufferedInputStream.java:201)
 at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:75)
 at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1440)
 ... 9 more
Want to Send SMS Using java program then click this Link and for more java program click this Link..
Do post your comments.