Saturday 24 October 2015

JavaMail Tutorial | How to read received mail

     JavaMail helps you to connect your mailing service with your custom software! In this tutorial  you are gonna use javamail to fetch the revieved mails and once received the mail is set to read.


Steps:
1.Download and add javamail library to your project!
2.Copy past the below java code to your class file.


Java:
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.util.Properties;  
 import java.util.concurrent.Executors;  
 import java.util.concurrent.ScheduledExecutorService;  
 import java.util.concurrent.TimeUnit;  
 import java.util.logging.Handler;  
 import javax.mail.Address;  
 import javax.mail.BodyPart;  
 import javax.mail.Flags;  
 import javax.mail.Folder;  
 import javax.mail.Message;  
 import javax.mail.MessagingException;  
 import javax.mail.Multipart;  
 import javax.mail.NoSuchProviderException;  
 import javax.mail.PasswordAuthentication;  
 import javax.mail.Session;  
 import javax.mail.Store;  
 import javax.mail.Flags.Flag;  
 import javax.mail.search.FlagTerm;  
 public class ReceiveMail {  
   Properties properties = null;  
   private Session session = null;  
   private Store store = null;  
   private Folder inbox = null;  
   private String userName = "XXXXXX@XXXXXX.com";// provide user name  
   private String password = "XXXXXXXXXX";// provide password  
   public ReceiveMail() {  
   }  
   public void readMails() {  
     properties = new Properties();  
     properties.setProperty("mail.host", "imap.gmail.com");  
     properties.setProperty("mail.port", "995");  
     properties.setProperty("mail.transport.protocol", "imaps");  
     session = Session.getInstance(properties,  
         new javax.mail.Authenticator() {  
           protected PasswordAuthentication getPasswordAuthentication() {  
             return new PasswordAuthentication(userName, password);  
           }  
         });  
     try {  
       store = session.getStore("imaps");  
       store.connect();  
       inbox = store.getFolder("INBOX");  
       inbox.open(Folder.READ_WRITE);  
       // search for all "unseen" messages  
       Flags seen = new Flags(Flags.Flag.SEEN);  
       FlagTerm unseenFlagTerm = new FlagTerm(seen, false);  
       Message messages[] = inbox.search(unseenFlagTerm);  
 //      Message messages[] = inbox.search(new FlagTerm(  
 //          new Flags(Flag.RECENT), false));  
 //        
       System.out.println("Number of mails = " + messages.length);  
                      for (int i = 0; i < messages.length; i++) {  
         Message message = messages[i];  
         Address[] from = message.getFrom();  
         System.out.println("-------------------------------");  
         System.out.println("Date : " + message.getSentDate());  
         System.out.println("From : " + from[0]);  
         System.out.println("Subject: " + message.getSubject());  
         System.out.println("Content : ");  
         processMessageBody(message);  
         System.out.println("--------------------------------");  
       }  
       inbox.close(true);  
       store.close();  
     } catch (NoSuchProviderException e) {  
       e.printStackTrace();  
     } catch (MessagingException e) {  
       //e.printStackTrace();  
          System.out.println("please connect to internet!");  
     }  
   }  
   public void processMessageBody(Message message) {  
     try {  
       Object content = message.getContent();  
       // check for string  
       // then check for multipart  
       if (content instanceof String) {  
         System.out.println(content);  
       } else if (content instanceof Multipart) {  
         Multipart multiPart = (Multipart) content;  
         procesMultiPart(multiPart);  
       } else if (content instanceof InputStream) {  
         InputStream inStream = (InputStream) content;  
         int ch;  
         while ((ch = inStream.read()) != -1) {  
           System.out.write(ch);  
         }      }  
     } catch (IOException e) {  
       e.printStackTrace();  
     } catch (MessagingException e) {  
       e.printStackTrace();  
     }  
   }  
   public void procesMultiPart(Multipart content) {  
     try {  
       int multiPartCount = content.getCount();  
       for (int i = 0; i < multiPartCount; i++) {  
         BodyPart bodyPart = content.getBodyPart(i);  
         Object o;  
         o = bodyPart.getContent();  
         if (o instanceof String) {  
              String[] splited = o.toString().split("<div");  
                       String msg = splited[0];  
                       if(!msg.equals(""))  
           System.out.println(msg);  
         } else if (o instanceof Multipart) {  
           procesMultiPart((Multipart) o);  
         }  
       }  
     } catch (IOException e) {  
       e.printStackTrace();  
     } catch (MessagingException e) {  
       e.printStackTrace();  
     }  
   }  
   public static void notifier(){  
        Runnable helloRunnable = new Runnable() {  
          public void run() {  
            // System.out.println("Hello world");  
                ReceiveMail sample = new ReceiveMail();  
             sample.readMails();  
          }  
        };  
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
        executor.scheduleAtFixedRate(helloRunnable, 0, 3, TimeUnit.SECONDS);   
   }  
   public static void main(String[] args) {  
        notifier();  
   }  
 }  




No comments:

Post a Comment