title: Sporadically getting javax.mail.FolderClosedException while reading gmail emails using javamail
body: <p>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().</p>
  
  <p>Here is my javamail code snippet:</p>
  
  <pre><code>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&lt;Message&gt; aList = new ArrayList&lt;Message&gt;();
              appendTextToConsole("Searching for appropriate messages!!");
              for (int ii = msgs.length - 1; ii &gt;= 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) &amp;&amp; !read) {
  //This line below gives FolderClosedException sporadically
  
                      Object content = msg.getContent();
                      if (content instanceof Multipart) {
                          Multipart mp = (Multipart) content;
                          for (int i = 0; i &lt; 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&lt;Element&gt; anchors = element.getElementsByTag("a");
                                  for (Element e : anchors) {
                                      if (e.attr("href").startsWith("https://www.google.com/url?rct=j&amp;sa=t&amp;url=")
                                              &amp;&amp; !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();
          }
  </code></pre>
  
  <p>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?</p>