Exemplo n.º 1
0
  protected boolean areMessagesInReverseOrder(Folder inbox) throws MessagingException {
    try {
      Message msgFirst = inbox.getMessage(1);
      Message msgLast = inbox.getMessage(inbox.getMessageCount());

      Date firstMessageDate = getDateToDetermineOrder(msgFirst);
      Date lastMessageDate = getDateToDetermineOrder(msgLast);
      return firstMessageDate != null
          && lastMessageDate != null
          && firstMessageDate.after(lastMessageDate);
    } catch (Exception e) {
      return false;
    }
  }
Exemplo n.º 2
0
  /**
   * Endpoint can be in the form of pop3://username:[email protected]
   *
   * @param endpointUri
   * @param timeout
   * @return
   * @throws Exception
   */
  public UMOMessage receive(UMOEndpointURI endpointUri, long timeout) throws Exception {
    initialise(endpointUri);

    long t0 = System.currentTimeMillis();
    if (timeout < 0) {
      timeout = Long.MAX_VALUE;
    }
    do {
      int count = folder.getMessageCount();
      if (count > 0) {
        Message message = folder.getMessage(1);
        // so we don't get the same message again
        message.setFlag(Flags.Flag.DELETED, true);
        return new MuleMessage(connector.getMessageAdapter(message));
      } else if (count == -1) {
        throw new MessagingException(
            "Cannot monitor folder: " + folder.getFullName() + " as folder is closed");
      }
      long sleep =
          Math.min(this.connector.getCheckFrequency(), timeout - (System.currentTimeMillis() - t0));
      if (sleep > 0) {
        if (logger.isDebugEnabled()) {
          logger.debug("No results, sleeping for " + sleep);
        }
        Thread.sleep(sleep);
      } else {
        logger.debug("Timeout");
        return null;
      }
    } while (true);
  }
Exemplo n.º 3
0
 public void flagAsDeleted(int[] messageIds) throws Exception {
   Folder fold = null;
   try {
     fold = getFolder();
     if (messageIds != null && messageIds.length > 0) {
       for (int i = 0; i < messageIds.length; i++) {
         try {
           if (messageIds[i] > 0) {
             Message msg = fold.getMessage(messageIds[i]);
             msg.setFlag(Flags.Flag.SEEN, true);
             msg.setFlag(Flags.Flag.DELETED, true);
           }
         } catch (Exception e) {
           log.debug("error while deleting messsage", e);
         }
       }
     }
   } catch (MessagingException e) {
     log.error("Could not delete message ids: " + messageIds, e);
     throw new MailboxActionException(e);
   } catch (IndexOutOfBoundsException e) {
     log.warn("Maybe you are double clicking the delete button. do it a little bit slowly :) ", e);
   } catch (Exception e) {
     log.error("Could not delete message ids: " + messageIds, e);
     throw new MailboxActionException(e);
   }
 }
Exemplo n.º 4
0
 /* (non-Javadoc)
  * @see org.claros.commons.mail.protocols.Protocol#deleteMessages(int[])
  */
 public ConnectionMetaHandler deleteMessages(int[] messageIds)
     throws MailboxActionException, SystemException, ConnectionException {
   Folder fold = null;
   try {
     fold = getFolder();
     if (messageIds != null && messageIds.length > 0) {
       for (int i = 0; i < messageIds.length; i++) {
         try {
           if (messageIds[i] > 0) {
             Message msg = fold.getMessage(messageIds[i]);
             msg.setFlag(Flags.Flag.DELETED, true);
           }
         } catch (Exception e) {
           log.debug("error while deleting messsage", e);
         }
       }
       fold.expunge();
     }
   } catch (MessagingException e) {
     log.error("Could not delete message ids: " + messageIds, e);
     throw new MailboxActionException(e);
   } catch (IndexOutOfBoundsException e) {
     log.error("Maybe you are double clicking the delete button", e);
   } catch (Exception e) {
     log.error("Could not delete message ids: " + messageIds, e);
     throw new MailboxActionException(e);
   } finally {
     closeFolder(fold);
     //			disconnect();
   }
   return handler;
 }
  @Override
  public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception {

    if (askGmailPassword || gmailPassword == null || gmailUsername == null) {
      Pair<String, String> credentials =
          GuiUtils.askCredentials(
              ConfigFetch.getSuperParentFrame(),
              "Enter Gmail Credentials",
              getGmailUsername(),
              getGmailPassword());
      if (credentials == null) return null;
      setGmailUsername(credentials.first());
      setGmailPassword(credentials.second());
      PluginUtils.saveProperties("conf/rockblock.props", this);
      askGmailPassword = false;
    }

    Properties props = new Properties();
    props.put("mail.store.protocol", "imaps");
    ArrayList<IridiumMessage> messages = new ArrayList<>();
    try {
      Session session = Session.getDefaultInstance(props, null);
      Store store = session.getStore("imaps");
      store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword());

      Folder inbox = store.getFolder("Inbox");
      inbox.open(Folder.READ_ONLY);
      int numMsgs = inbox.getMessageCount();

      for (int i = numMsgs; i > 0; i--) {
        Message m = inbox.getMessage(i);
        if (m.getReceivedDate().before(timeSince)) {
          break;
        } else {
          MimeMultipart mime = (MimeMultipart) m.getContent();
          for (int j = 0; j < mime.getCount(); j++) {
            BodyPart p = mime.getBodyPart(j);
            Matcher matcher = pattern.matcher(p.getContentType());
            if (matcher.matches()) {
              InputStream stream = (InputStream) p.getContent();
              byte[] data = IOUtils.toByteArray(stream);
              IridiumMessage msg = process(data, matcher.group(1));
              if (msg != null) messages.add(msg);
            }
          }
        }
      }
    } catch (NoSuchProviderException ex) {
      ex.printStackTrace();
      System.exit(1);
    } catch (MessagingException ex) {
      ex.printStackTrace();
      System.exit(2);
    }

    return messages;
  }
 protected Message getNextMessage() throws MessagingException {
   if (getMessageCount() > 0) {
     Message message = folder.getMessage(1);
     if (!message.isExpunged()) {
       return message;
     }
   }
   return null;
 }
Exemplo n.º 7
0
 /**
  * @param msgId
  * @throws Exception
  */
 public void markAsRead(Long msgId) throws Exception {
   Folder f = getFolder();
   try {
     Message msg = f.getMessage(msgId.intValue());
     msg.setFlag(Flags.Flag.SEEN, true);
   } catch (MessagingException e) {
     log.warn("Marking as Read not worked.", e);
   }
 }
 private Message retrieveViaImap(String host, int port, String user, String password)
     throws MessagingException {
   Properties props = new Properties();
   props.setProperty("mail.store.protocol", "imap");
   props.setProperty("mail.imap.port", String.valueOf(port));
   Session session = Session.getInstance(props, null);
   Store store = session.getStore();
   store.connect(host, user, password);
   Folder inbox = store.getFolder("INBOX");
   inbox.open(Folder.READ_ONLY);
   int messageCount = inbox.getMessageCount();
   return messageCount == 0 ? null : inbox.getMessage(1);
 }
  /**
   * Test that FolderClosedException is thrown when the timeout occurs when reading the message
   * body.
   */
  @Test
  public void testFolderClosedExceptionBody() {
    TestServer server = null;
    try {
      final POP3Handler handler = new POP3HandlerTimeoutBody();
      server = new TestServer(handler);
      server.start();
      Thread.sleep(1000);

      final Properties properties = new Properties();
      properties.setProperty("mail.pop3.host", "localhost");
      properties.setProperty("mail.pop3.port", "" + server.getPort());
      final Session session = Session.getInstance(properties);
      // session.setDebug(true);

      final Store store = session.getStore("pop3");
      try {
        store.connect("test", "test");
        final Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        Message msg = folder.getMessage(1);
        try {
          msg.getContent();
        } catch (IOException ioex) {
          // expected
          // first attempt detects error return from server
        }
        // second attempt detects closed connection from server
        msg.getContent();

        // Check
        assertFalse(folder.isOpen());
      } catch (FolderClosedException ex) {
        // success!
      } finally {
        store.close();
      }
    } catch (final Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    } finally {
      if (server != null) {
        server.quit();
      }
    }
  }
Exemplo n.º 10
0
 public Message getMessage(int messageId)
     throws MailboxActionException, SystemException, ConnectionException, Exception {
   Message msg = null;
   Folder fold = null;
   try {
     try {
       fold = getFolder();
       msg = fold.getMessage(messageId);
     } catch (Exception e) {
       System.out.println("Could not fetch message body from remote server.");
       throw new MailboxActionException(e);
     }
   } catch (Exception e) {
     throw e;
   }
   return msg;
 }
  private Object receiveMail() throws Exception {
    Folder folder = null;
    Store store = null;
    ConfigurationPropertyManager configManager =
        ConfigurationPropertyManager.getConfigurationPropertyManager();
    final String email_address = configManager.getPropValues("gmail_address");
    final String password = configManager.getPropValues("gmail_pw");

    try {
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");

      // Session session = Session.getDefaultInstance(props, null);
      Session session = Session.getInstance(props, new GMailAuthenticator(email_address, password));
      store = session.getStore("imaps");
      store.connect("imap.gmail.com", email_address, password);
      folder = store.getFolder("Inbox");
      folder.open(Folder.READ_WRITE);
      // Message messages[] = folder.getMessages();
      // search for all "unseen" messages
      Flags seen = new Flags(Flags.Flag.SEEN);
      FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
      Message messages[] = folder.search(unseenFlagTerm);

      for (int i = 0; i < messages.length; i++) {
        folder.getMessage(
            messages[i].getMessageNumber()); // this will mark the retrieved messages as READ	    	
      }
      String s = updateEmailrepository(messages);
      // System.out.println(s);
      StringTerm st = new StringTermImpl(s);
      return st;

    } catch (Exception e) {
      System.out.println(e.toString());
    } finally {
      if (folder != null) {
        folder.close(true);
      }
    }
    return null;
  }
Exemplo n.º 12
0
 /* (non-Javadoc)
  * @see org.claros.commons.mail.protocols.FetchProtocol#deleteMessages(int[])
  */
 public ConnectionMetaHandler deleteMessages(int[] messageIds)
     throws MailboxActionException, SystemException, ConnectionException {
   Folder fold = null;
   try {
     fold = getFolder();
     if (messageIds != null && messageIds.length > 0) {
       for (int i = 0; i < messageIds.length; i++) {
         Message msg = fold.getMessage(messageIds[i]);
         msg.setFlag(Flags.Flag.DELETED, true);
       }
     }
     // fold.expunge();
     disconnect();
     connect(Constants.CONNECTION_READ_WRITE);
     return handler;
   } catch (Exception e) {
     pop3Folders.put(auth.getUsername(), null);
     System.out.println("Could not delete message ids: " + messageIds);
     throw new MailboxActionException(e);
   }
 }
  public ClienteEmailCentralServicoDTO getMessages(
      DocumentHTML document, HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    ClienteEmailCentralServicoDTO clienteEmailCentralServicoDto =
        new ClienteEmailCentralServicoDTO();
    clienteEmailCentralServicoDto.setResultSucess(true);

    try {
      if (CONEXAO_EMAIL_SERVIDOR.equals("")
          || CONEXAO_EMAIL_PROVIDER.equals("")
          || CONEXAO_EMAIL_CAIXA.equals("")
          || CONEXAO_EMAIL_SENHA.equals("")
          || CONEXAO_EMAIL_PASTA.equals("")) {
        clienteEmailCentralServicoDto.setResultSucess(false);
        clienteEmailCentralServicoDto.setResultMessage(
            UtilI18N.internacionaliza(
                request, "clienteEmailCentralServico.problemasRealizarleituraEmailsParametros"));
      } else {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", CONEXAO_EMAIL_PROVIDER);

        props.setProperty("mail.imaps.auth.plain.disable", "true");
        props.setProperty("mail.imaps.ssl.trust", "*");
        // props.setProperty("mail.debug", "true");

        if (!CONEXAO_EMAIL_PORTA.equals(""))
          props.setProperty("mail." + CONEXAO_EMAIL_PROVIDER + ".port", CONEXAO_EMAIL_PORTA);

        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(CONEXAO_EMAIL_SERVIDOR, CONEXAO_EMAIL_CAIXA, CONEXAO_EMAIL_SENHA);

        Folder inbox = store.getFolder(CONEXAO_EMAIL_PASTA);
        inbox.open(Folder.READ_WRITE);

        Message[] messages = inbox.getMessages();

        if (messages != null && messages.length > 0) {
          ArrayList<ClienteEmailCentralServicoMessagesDTO> emailMessages =
              new ArrayList<ClienteEmailCentralServicoMessagesDTO>();
          for (Message message : messages) {
            ClienteEmailCentralServicoMessagesDTO clienteEmailMessagesDto =
                new ClienteEmailCentralServicoMessagesDTO();

            MimeMessage m = (MimeMessage) inbox.getMessage(message.getMessageNumber());
            clienteEmailMessagesDto.setMessageId(m.getMessageID());
            clienteEmailMessagesDto.setMessageNumber(message.getMessageNumber());

            Address[] in = message.getFrom();
            clienteEmailMessagesDto.setMessageEmail(
                (in == null ? null : ((InternetAddress) in[0]).getAddress()));

            clienteEmailMessagesDto.setMessageSubject(message.getSubject());
            clienteEmailMessagesDto.setMessageReceivedDate(message.getReceivedDate());
            // clienteEmailMessagesDto.setSeen(message.isSet(Flags.Flag.SEEN));
            clienteEmailMessagesDto.setSeen(true);

            emailMessages.add(clienteEmailMessagesDto);
          }

          clienteEmailCentralServicoDto.setEmailMessages(emailMessages);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      clienteEmailCentralServicoDto.setResultSucess(false);
      clienteEmailCentralServicoDto.setResultMessage(
          UtilI18N.internacionaliza(
              request, "clienteEmailCentralServico.problemasRealizarleituraEmails"));
    }

    return clienteEmailCentralServicoDto;
  }
Exemplo n.º 14
0
  public static void ClaimsMsgShow(
      java.lang.String argvs[],
      Folder folder,
      Store store,
      biz.systempartners.claims.ClaimsViewer claimsViewer) {
    if (claimsViewer == null) {}

    int msgnum = -1;
    int optind = 0;
    InputStream msgStream = System.in;

    if (argvs != null) {

      for (optind = 0; optind < argvs.length; optind++) {
        if (argvs[optind].equals("-T")) {
          protocol = argvs[++optind];
        } else if (argvs[optind].equals("-H")) {
          host = argvs[++optind];
        } else if (argvs[optind].equals("-U")) {
          user = argvs[++optind];
        } else if (argvs[optind].equals("-P")) {
          password = argvs[++optind];
        } else if (argvs[optind].equals("-v")) {
          verbose = true;
        } else if (argvs[optind].equals("-D")) {
          debug = true;
        } else if (argvs[optind].equals("-f")) {
          mbox = argvs[++optind];
        } else if (argvs[optind].equals("-L")) {
          url = argvs[++optind];
        } else if (argvs[optind].equals("-p")) {
          port = Integer.parseInt(argvs[++optind]);
        } else if (argvs[optind].equals("-s")) {
          showStructure = true;
        } else if (argvs[optind].equals("-S")) {
          saveAttachments = true;
        } else if (argvs[optind].equals("-m")) {
          showMessage = true;
        } else if (argvs[optind].equals("-a")) {
          showAlert = true;
        } else if (argvs[optind].equals("--")) {
          optind++;
          break;
        } else if (argvs[optind].startsWith("-")) {
          System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
          System.out.println("\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]");
          System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] < msg");
          System.exit(1);
        } else {
          break;
        }
      }
    }

    try {
      if (optind < argvs.length) msgnum = Integer.parseInt(argvs[optind]);
      //            msgnum = 1;

      // Get a Properties object
      Properties props = System.getProperties();

      // Get a Session object
      Session session = Session.getInstance(props, null);
      session.setDebug(debug);

      if (showMessage) {
        MimeMessage msg = new MimeMessage(session, msgStream);
        dumpPart(msg, claimsViewer);
        //	System.exit(0);
      }
      /*
                 // Get a Store object
                 Store store = null;
                 if (url != null) {
                     URLName urln = new URLName(url);
                     store = session.getStore(urln);
                     if (showAlert) {
                         store.addStoreListener(new StoreListener() {
                             public void notification(StoreEvent e) {
                                 String s;
                                 if (e.getMessageType() == StoreEvent.ALERT)
                                     s = "ALERT: ";
                                 else
                                     s = "NOTICE: ";
                                 System.out.println(s + e.getMessage());
                             }
                         });
                     }
                     store.connect();
                 } else {
                     if (protocol != null)
                         store = session.getStore(protocol);
                     else
                         store = session.getStore();

                     // Connect
                     if (host != null || user != null || password != null)
                         store.connect(host, port, user, password);
                     else
                         store.connect();
                 }


                 // Open the Folder

                 Folder folder = store.getDefaultFolder();
                 if (folder == null) {
                     System.out.println("No default folder");
                     System.exit(1);
                 }
      */
      //	    folder = folder.getFolder(mbox);
      if (folder == null) {
        System.out.println("Invalid folder");
        System.exit(1);
      }

      // try to open read/write and if that fails try read-only
      try {
        folder.open(Folder.READ_WRITE);
      } catch (MessagingException ex) {
        folder.open(Folder.READ_ONLY);
      }
      int totalMessages = folder.getMessageCount();

      if (totalMessages == 0) {
        System.out.println("Empty folder");
        folder.close(false);
        store.close();
        System.exit(1);
      }

      if (verbose) {
        int newMessages = folder.getNewMessageCount();
        System.out.println("Total messages = " + totalMessages);
        System.out.println("New messages = " + newMessages);
        System.out.println("-------------------------------");
      }

      if (msgnum == -1) {
        // Attributes & Flags for all messages ..
        Message[] msgs = folder.getMessages();

        // Use a suitable FetchProfile
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfile.Item.FLAGS);
        fp.add("X-Mailer");
        folder.fetch(msgs, fp);

        for (int i = 0; i < msgs.length; i++) {
          System.out.println("--------------------------");
          System.out.println("MESSAGE #" + (i + 1) + ":");
          dumpEnvelope(msgs[i]);
          // dumpPart(msgs[i]);
        }
      } else {
        Message[] msgs = folder.getMessages();
        for (int n = 0; n < msgs.length; n++) {
          System.out.println("Getting message number: " + n + 1);
          Message m = null;

          try {
            m = folder.getMessage(msgnum + 1);
            // m.setDisposition(
            dumpPart(m, claimsViewer);
            //        m.setExpunged(true);
          } catch (IndexOutOfBoundsException iex) {
            System.out.println("Message number out of range");
          }
        }
        folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true);
      }
      //            folder.expunge();
      folder.close(true);

      store.close();
    } catch (Exception ex) {
      System.out.println("Oops, got exception! " + ex.getMessage());
      ex.printStackTrace();
      //	    System.exit(1);
    }
    //	System.exit(0);
  }
Exemplo n.º 15
0
  /**
   * After a mailbox has been opened, search through the retrieved messages for a matching subject.
   *
   * @param mailParms
   * @param mailFolder
   * @return a PollStatus indicative of the success of matching a subject or just retieving mail
   *     folder contents... dependent on configuration.
   */
  private PollStatus processMailSubject(
      final MailTransportParameters mailParms, final Folder mailFolder) {
    PollStatus status = PollStatus.unknown();
    try {
      final String subject = computeMatchingSubject(mailParms);
      if (mailFolder.isOpen() && subject != null) {
        final Message[] mailMessages = mailFolder.getMessages();
        final SearchTerm searchTerm = new SubjectTerm(subject);
        final SearchTerm deleteTerm = new HeaderTerm(MTM_HEADER_KEY, m_headerValue);

        LOG.debug(
            "searchMailSubject: searching {} message(s) for subject '{}'",
            mailMessages.length,
            subject);

        boolean delete = false;
        boolean found = false;
        for (int i = 1; i <= mailMessages.length; i++) {
          final Message mailMessage = mailFolder.getMessage(i);

          LOG.debug("searchMailSubject: retrieved message subject '{}'", mailMessage.getSubject());

          if (mailMessage.match(searchTerm)) {
            found = true;
            LOG.debug("searchMailSubject: message with subject '{}' found.", subject);

            if (mailParms.isEnd2EndTestInProgress()) {
              if (!delete)
                LOG.debug(
                    "searchMailSubject: flagging message with subject '{}' for deletion for end2end test.",
                    subject);
              delete = true;
            }
          }

          final boolean deleteAllMail = mailParms.getReadTest().isDeleteAllMail();
          final boolean foundMTMHeader = mailMessage.match(deleteTerm);
          LOG.debug(
              "searchMailSubject: deleteAllMail = {}, MTM header found = {}",
              Boolean.toString(deleteAllMail),
              Boolean.toString(foundMTMHeader));

          if (deleteAllMail) {
            if (!delete)
              LOG.debug(
                  "searchMailSubject: flagging message with subject '{}' for deletion because deleteAllMail is set.",
                  subject);
            delete = true;
          } else if (foundMTMHeader) {
            if (!delete)
              LOG.debug(
                  "searchMailSubject: flagging message with subject '{}' for deletion because we sent it (found header {}={})",
                  subject,
                  MTM_HEADER_KEY,
                  m_headerValue);
            delete = true;
          }

          if (delete) {
            mailMessage.setFlag(Flag.DELETED, true);
          }

          // since we want to delete old messages matchin MTM_HEADER_KEY, we can't break early
          // if (found) break;
        }

        if (!found) {
          LOG.debug("searchMailSubject: message with subject: '{}' NOT found.", subject);
          status =
              PollStatus.down(
                  "searchMailSubject: matching test message: '" + subject + "', not found.");
        } else {
          status = PollStatus.available();
        }
      }
    } catch (final MessagingException e) {
      return PollStatus.down(e.getLocalizedMessage());
    }

    return status;
  }
  public ClienteEmailCentralServicoDTO readMessage(
      DocumentHTML document,
      HttpServletRequest request,
      HttpServletResponse response,
      String messageId)
      throws Exception {
    ClienteEmailCentralServicoDTO clienteEmailCentralServicoDto =
        new ClienteEmailCentralServicoDTO();
    clienteEmailCentralServicoDto.setResultSucess(true);

    try {
      if (CONEXAO_EMAIL_SERVIDOR.equals("")
          || CONEXAO_EMAIL_PROVIDER.equals("")
          || CONEXAO_EMAIL_CAIXA.equals("")
          || CONEXAO_EMAIL_SENHA.equals("")
          || CONEXAO_EMAIL_PASTA.equals("")) {
        clienteEmailCentralServicoDto.setResultSucess(false);
        clienteEmailCentralServicoDto.setResultMessage(
            UtilI18N.internacionaliza(
                request, "clienteEmailCentralServico.problemasRealizarleituraEmailsParametros"));
      } else {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", CONEXAO_EMAIL_PROVIDER);

        props.setProperty("mail.imaps.auth.plain.disable", "true");
        props.setProperty("mail.imaps.ssl.trust", "*");
        // props.setProperty("mail.debug", "true");

        if (!CONEXAO_EMAIL_PORTA.equals(""))
          props.setProperty("mail." + CONEXAO_EMAIL_PROVIDER + ".port", CONEXAO_EMAIL_PORTA);

        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(CONEXAO_EMAIL_SERVIDOR, CONEXAO_EMAIL_CAIXA, CONEXAO_EMAIL_SENHA);

        Folder inbox = store.getFolder(CONEXAO_EMAIL_PASTA);
        inbox.open(Folder.READ_WRITE);

        SearchTerm searchTerm = new MessageIDTerm(messageId);
        Message[] messages = inbox.search(searchTerm);

        if (messages != null && messages.length > 0) {
          ArrayList<ClienteEmailCentralServicoMessagesDTO> emailMessages =
              new ArrayList<ClienteEmailCentralServicoMessagesDTO>();
          for (Message message : messages) {
            ClienteEmailCentralServicoMessagesDTO clienteEmailMessagesDto =
                new ClienteEmailCentralServicoMessagesDTO();

            MimeMessage m = (MimeMessage) inbox.getMessage(message.getMessageNumber());
            clienteEmailMessagesDto.setMessageId(m.getMessageID());
            clienteEmailMessagesDto.setMessageNumber(message.getMessageNumber());

            Address[] in = message.getFrom();
            clienteEmailMessagesDto.setMessageEmail(
                (in == null ? null : ((InternetAddress) in[0]).getAddress()));

            clienteEmailMessagesDto.setMessageSubject(message.getSubject());
            clienteEmailMessagesDto.setMessageReceivedDate(message.getReceivedDate());
            clienteEmailMessagesDto.setSeen(message.isSet(Flags.Flag.SEEN));

            Object objRef = message.getContent();
            String content = "";

            if (!(objRef instanceof Multipart)) {
              content = (String) message.getContent();
            } else {
              Multipart mp = (Multipart) message.getContent();
              BodyPart bp = mp.getBodyPart(0);

              content = getContent(bp);
            }

            if (content != null) {
              // content = content.replaceAll("(\r\n|\r|\n)", "<br />");
              content = StringEscapeUtils.escapeEcmaScript(content);

              clienteEmailMessagesDto.setMessageContent(content);
            }

            emailMessages.add(clienteEmailMessagesDto);
          }

          clienteEmailCentralServicoDto.setEmailMessages(emailMessages);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      clienteEmailCentralServicoDto.setResultSucess(false);
      clienteEmailCentralServicoDto.setResultMessage(
          UtilI18N.internacionaliza(
              request, "clienteEmailCentralServico.problemasRealizarleituraEmails"));
    }

    return clienteEmailCentralServicoDto;
  }
  public ClienteEmailCentralServicoDTO getMessagesByLimitAndNoRequest(
      DocumentHTML document, HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    EmailSolicitacaoServicoService emailSolicitacaoServicoService =
        (EmailSolicitacaoServicoService)
            ServiceLocator.getInstance()
                .getService(
                    EmailSolicitacaoServicoService.class, WebUtil.getUsuarioSistema(request));
    ClienteEmailCentralServicoDTO clienteEmailCentralServicoDto =
        new ClienteEmailCentralServicoDTO();
    clienteEmailCentralServicoDto.setResultSucess(true);

    try {
      if (CONEXAO_EMAIL_SERVIDOR.equals("")
          || CONEXAO_EMAIL_PROVIDER.equals("")
          || CONEXAO_EMAIL_CAIXA.equals("")
          || CONEXAO_EMAIL_SENHA.equals("")
          || CONEXAO_EMAIL_PASTA.equals("")) {
        clienteEmailCentralServicoDto.setResultSucess(false);
        clienteEmailCentralServicoDto.setResultMessage(
            UtilI18N.internacionaliza(
                request, "clienteEmailCentralServico.problemasRealizarleituraEmailsParametros"));
      } else {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", CONEXAO_EMAIL_PROVIDER);

        props.setProperty("mail.imaps.auth.plain.disable", "true");
        props.setProperty("mail.imaps.ssl.trust", "*");
        // props.setProperty("mail.debug", "true");

        if (!CONEXAO_EMAIL_PORTA.equals(""))
          props.setProperty("mail." + CONEXAO_EMAIL_PROVIDER + ".port", CONEXAO_EMAIL_PORTA);

        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(CONEXAO_EMAIL_SERVIDOR, CONEXAO_EMAIL_CAIXA, CONEXAO_EMAIL_SENHA);

        Folder inbox = store.getFolder(CONEXAO_EMAIL_PASTA);
        inbox.open(Folder.READ_WRITE);

        Message[] messages = inbox.getMessages();

        if (messages != null && messages.length > 0) {
          ArrayUtils.reverse(messages);

          Integer limiteEmails = 10;

          try {
            limiteEmails = Integer.parseInt(CONEXAO_EMAIL_LIMITE);
          } catch (NumberFormatException e) {
            e.printStackTrace();
            limiteEmails = 10;
          }

          ArrayList<ClienteEmailCentralServicoMessagesDTO> emailMessages =
              new ArrayList<ClienteEmailCentralServicoMessagesDTO>();

          for (Message message : messages) {
            if (emailMessages.size() < limiteEmails) {
              MimeMessage m = (MimeMessage) inbox.getMessage(message.getMessageNumber());
              EmailSolicitacaoServicoDTO colEmailDto =
                  emailSolicitacaoServicoService.getEmailByIdMessage(m.getMessageID());

              if (colEmailDto == null) {
                ClienteEmailCentralServicoMessagesDTO clienteEmailMessagesDto =
                    new ClienteEmailCentralServicoMessagesDTO();

                clienteEmailMessagesDto.setMessageId(m.getMessageID());
                clienteEmailMessagesDto.setMessageNumber(message.getMessageNumber());

                Address[] in = message.getFrom();
                clienteEmailMessagesDto.setMessageEmail(
                    (in == null ? null : ((InternetAddress) in[0]).getAddress()));

                clienteEmailMessagesDto.setMessageSubject(message.getSubject());
                clienteEmailMessagesDto.setMessageReceivedDate(message.getReceivedDate());

                // clienteEmailMessagesDto.setSeen(message.isSet(Flags.Flag.SEEN)); //Atrapalha a
                // performance
                clienteEmailMessagesDto.setSeen(true);

                emailMessages.add(clienteEmailMessagesDto);
              }
            } else {
              break;
            }
          }

          clienteEmailCentralServicoDto.setEmailMessages(emailMessages);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      clienteEmailCentralServicoDto.setResultSucess(false);
      clienteEmailCentralServicoDto.setResultMessage(
          UtilI18N.internacionaliza(
              request, "clienteEmailCentralServico.problemasRealizarleituraEmails"));
    }

    return clienteEmailCentralServicoDto;
  }