Friday, October 28, 2011

Check mails using Java

 Instead of automating logging into gmail and checking each mail use the below code to get the contents of required mail 

Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");
        try {
            Session session = Session.getDefaultInstance(props, null);
            Store store = session.getStore("imaps");
            store.connect("imap.gmail.com", "xxxxx@gmail.com", "xxxxxx");
            System.out.println("Store : "+store);

            Folder inbox = store.getFolder("Inbox");
            inbox.open(Folder.READ_ONLY);
            System.out.println("Messge count "+inbox.getUnreadMessageCount());

            Message messages[] = inbox.search(new SubjectTerm("Flags.Flag (JavaMail API documentation)"), inbox.getMessages());
            Date date = new Date();
            System.out.println("Date "+date);

            for (Message message : messages) {
                System.out.println("Seen Flag "+message.isSet(Flags.Flag.SEEN));
                System.out.println("Messge Send Date "+message.getSentDate());

                if(!message.isSet(Flags.Flag.SEEN)){
                    if(date.compareTo(message.getSentDate())<=0){
                        String line;
                        StringBuffer buffer = new StringBuffer();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(message.getInputStream()));
                        while ((line = reader.readLine()) != null) {
                            buffer.append(line);
                        }
                        System.out.println(buffer);
                    }
                }
            }
        } catch (MessagingException e) {
            e.printStackTrace();
            System.exit(2);
        }

No comments:

Post a Comment