Search This Blog

Tuesday, 2 September 2014

Reading Email and Search the mails based on subject

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sravan;

/**
 *
 * @author sravan.k
 */
import java.util.*;
import javax.mail.*;


public class ReadingMail {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");//setting the properties for imap .it is advanced server
        try {
            Session session = Session.getInstance(props, null);//getting the session
            Store store = session.getStore();//getting the store using session object
            store.connect("imap.gmail.com", "username@gmail.com", "your password");
            Folder inbox = store.getFolder("INBOX");//getting the inbox folder
            inbox.open(Folder.READ_ONLY);//open it in read only mode
          String sub = "123456789";//search subject. change accordingly
          int x =  inbox.getMessageCount();//total number mails in your acccount
          int i=0;
            System.out.println("inbox::"+x);
       
            Message messages[] = inbox.getMessages();
            for(i=x-1;i>x-50;i--){ ///reading last 50 messages and selecting subject 123456789
                Message msg = messages[i];
                if(sub.equalsIgnoreCase(msg.getSubject()))
                {
                    System.out.println("Recieved date::"+msg.getReceivedDate());//getting Received date\
                    System.out.println("Sent Date::"+msg.getSentDate());
                  //using getFrom() methos in message object we will get the address.and bodypart() method we will get the content
                   
                }
               
               
               
            }
           
           
        } catch (Exception mex) {
            mex.printStackTrace();
        }
    }
}

No comments:

Post a Comment