rahulserver
rahulserver

Reputation: 11205

Sporadically getting javax.mail.FolderClosedException while reading gmail emails using javamail

I am trying to read javamail inbox and perform search. For this, I am fetching the latest 100 messages and then I am iterating through each to see if they have the sender for whom I am searching for. If its matching, I get its content via getContent().

Here is my javamail code snippet:

try {

            Properties properties = new Properties();
            properties.setProperty("mail.store.protocol", "imap");
            properties.put("mail.imaps.starttls.enable", "true");
            properties.put("mail.imap.socketFactory.port", "587");
            System.setProperty("javax.net.debug", "ssl");
            System.out.println("prop " + properties.getProperty("mail.smtp.port"));

            Session session = Session.getDefaultInstance(properties, null);
            // session.setDebug(true);
            Store store = null;
            store = session.getStore("imaps");
            store.connect("imap.gmail.com", username, password);
            Folder inbox;
            inbox = store.getFolder("Inbox");
      /* Others GMail folders :
       * [Gmail]/All Mail   This folder contains all of your Gmail messages.
       * [Gmail]/Drafts     Your drafts.
       * [Gmail]/Sent Mail  Messages you sent to other people.
       * [Gmail]/Spam       Messages marked as spam.
       * [Gmail]/Starred    Starred messages.
       * [Gmail]/Trash      Messages deleted from Gmail.
       */
            inbox.open(Folder.READ_WRITE);

            Message msgs[] = inbox.getMessages(inbox.getMessageCount() - lastHistory, inbox.getMessageCount());
            System.out.println("MSgs.length " + msgs.length);
            ArrayList<Message> aList = new ArrayList<Message>();
            appendTextToConsole("Searching for appropriate messages!!");
            for (int ii = msgs.length - 1; ii >= 0; ii--) {
                Message msg = msgs[ii];
                Address[] in = msg.getFrom();
                String sender = InternetAddress.toString(in);
                System.out.println((++index) + "Sender: " + sender);
                boolean read = msg.isSet(Flags.Flag.SEEN);
                if (sender.contains(googleId) && !read) {
//This line below gives FolderClosedException sporadically

                    Object content = msg.getContent();
                    if (content instanceof Multipart) {
                        Multipart mp = (Multipart) content;
                        for (int i = 0; i < mp.getCount(); i++) {
                            BodyPart bp = mp.getBodyPart(i);
                            if (Pattern
                                    .compile(Pattern.quote("text/html"),
                                            Pattern.CASE_INSENSITIVE)
                                    .matcher(bp.getContentType()).find()) {
                                // found html part
                                String html = (String) bp.getContent();
                                Element element = Jsoup.parse(html);
                                List<Element> anchors = element.getElementsByTag("a");
                                for (Element e : anchors) {
                                    if (e.attr("href").startsWith("https://www.google.com/url?rct=j&sa=t&url=")
                                            && !e.attr("style").equalsIgnoreCase("text-decoration:none")) {
                                        String url = e.attr("href");
                                        String title = e.text();
                                        String agency = e.parent().parent().child(1).child(0).child(0).text();
                                        String message = e.parent().parent().child(1).child(0).child(1).text();
                                        String flagUrl = e.parent().parent().child(1).child(1).child(0).child(0).child(3).child(0).attr("href");
                                        System.out.println("URL: " + url);
                                        System.out.println("Title: " + title);
                                        System.out.println("agency: " + agency);
                                        System.out.println("Message: " + message);
                                        System.out.println("flagURL: " + flagUrl);
                                        AbstractMessage ams = new AbstractMessage(url, title, agency, message, flagUrl);
                                        aMsgs.add(ams);
                                    }
                                }
                                //System.out.println((String) bp.getContent());
                            } else {
                                // some other bodypart...
                            }
                        }
                        try {
                            inbox.close(true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            appendTextToConsole("Done searching for appropriate messages!!");
        } catch (Exception mex) {
            appendTextToConsole(mex.getMessage());
            mex.printStackTrace();
        }

But the most irritating thing is that after fetching a few messages, sporadically a javax.mail.FolderClosedException is thrown due to unknown reasons. Now my question is that how do I deal with this scenario? And how do ideal mail clients made using javamail deal with it?

Upvotes: 0

Views: 1771

Answers (1)

Bill Shannon
Bill Shannon

Reputation: 29971

Turn on session debugging and you might get more clues as to what's going on.

Note that the server will close the connection if you're not using it. And of course all sorts of network failures are possible.

Upvotes: 1

Related Questions