Example usage for javax.mail Folder getMessages

List of usage examples for javax.mail Folder getMessages

Introduction

In this page you can find the example usage for javax.mail Folder getMessages.

Prototype

public synchronized Message[] getMessages() throws MessagingException 

Source Link

Document

Get all Message objects from this Folder.

Usage

From source file:com.silverpeas.mailinglist.service.job.TestYahooMailConnection.java

@Test
public void testOpenImapConnection() throws Exception {
    Store mailAccount = null;/*  ww  w  .  j av  a 2 s .  co  m*/
    Folder inbox = null;
    Session mailSession = Session.getInstance(System.getProperties());
    try {
        mailSession.setDebug(true);
        mailAccount = mailSession.getStore(props.getProperty("mail.server.protocol"));
        mailAccount.connect(props.getProperty("mail.server.host"),
                Integer.parseInt(props.getProperty("mail.server.port")), props.getProperty("mail.server.login"),
                props.getProperty("mail.server.password"));
        inbox = mailAccount.getFolder("INBOX");
        if (inbox == null) {
            throw new MessagingException("No POP3 INBOX");
        }
        // -- Open the folder for read write --
        inbox.open(Folder.READ_WRITE);

        // -- Get the message wrappers and process them --
        javax.mail.Message[] msgs = inbox.getMessages();
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.FLAGS);
        inbox.fetch(msgs, profile);
        MailProcessor processor = new MailProcessor();
        MessageListener mailingList = mock(MessageListener.class);
        when(mailingList.checkSender(anyString())).thenReturn(Boolean.TRUE);
        when(mailingList.getComponentId()).thenReturn("mailingList38");
        MessageEvent event = new MessageEvent();
        for (javax.mail.Message message : msgs) {
            processor.prepareMessage((MimeMessage) message, mailingList, event);
        }
        assertThat(event.getMessages(), is(notNullValue()));
        assertThat(event.getMessages().size(), is(msgs.length));
        for (com.silverpeas.mailinglist.service.model.beans.Message message : event.getMessages()) {
            assertThat(message, is(notNullValue()));
            assertThat(message.getMessageId(), is(notNullValue()));
        }
    } finally {
        // -- Close down nicely --
        if (inbox != null) {
            inbox.close(false);
        }
        if (mailAccount != null) {
            mailAccount.close();
        }
    }
}

From source file:org.exist.xquery.modules.mail.MessageListFunctions.java

private Sequence getMessageList(Sequence[] args, Sequence contextSequence) throws XPathException {
    Message[] msgList;/*from www .  java 2s.  com*/

    // was a folder handle specified?
    if (args[0].isEmpty()) {
        throw (new XPathException(this, "Folder handle not specified"));
    }

    // get the Folder
    long folderHandle = ((IntegerValue) args[0].itemAt(0)).getLong();
    Folder folder = MailModule.retrieveFolder(context, folderHandle);
    if (folder == null) {
        throw (new XPathException(this, "Invalid Folder handle specified"));
    }

    try {
        msgList = folder.getMessages();
        prefetchMessages(folder, msgList);
    } catch (MessagingException me) {
        throw (new XPathException(this, "Failed to get mail list", me));
    }

    // save the message list and return the handle of the message list

    return (new IntegerValue(MailModule.storeMessageList(context, msgList, folderHandle)));
}

From source file:EmailBean.java

private void handleMessages(HttpServletRequest request, PrintWriter out) throws IOException, ServletException {

    HttpSession httpSession = request.getSession();
    String user = (String) httpSession.getAttribute("user");
    String password = (String) httpSession.getAttribute("pass");
    String popAddr = (String) httpSession.getAttribute("pop");

    Store popStore = null;//  ww w  . j  a v  a2 s  . com
    Folder folder = null;

    if (!check(popAddr))
        popAddr = EmailBean.DEFAULT_SERVER;

    try {

        if ((!check(user)) || (!check(password)))
            throw new ServletException("A valid username and password is required to check email.");

        Properties properties = System.getProperties();

        Session session = Session.getDefaultInstance(properties);

        popStore = session.getStore("pop3");

        popStore.connect(popAddr, user, password);

        folder = popStore.getFolder("INBOX");

        if (!folder.exists())
            throw new ServletException("An 'INBOX' folder does not exist for the user.");

        folder.open(Folder.READ_ONLY);

        Message[] messages = folder.getMessages();
        int msgLen = messages.length;

        if (msgLen == 0)
            out.println("<h2>The INBOX folder does not yet contain any email messages.</h2>");

        for (int i = 0; i < msgLen; i++) {
            displayMessage(messages[i], out);
            out.println("<br /><br />");
        }

    } catch (Exception exc) {

        out.println("<h2>Sorry, an error occurred while accessing the email messages.</h2>");
        out.println(exc.toString());

    } finally {
        try {
            if (folder != null)
                folder.close(false);

            if (popStore != null)
                popStore.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

@Test
public void testNullMessages() throws Exception {
    Message message1 = mock(Message.class);
    Message message2 = mock(Message.class);
    final Message[] messages1 = new Message[] { null, null, message1 };
    final Message[] messages2 = new Message[] { message2 };
    final SearchTermStrategy searchTermStrategy = mock(SearchTermStrategy.class);
    class TestReceiver extends ImapMailReceiver {

        private boolean firstDone;

        TestReceiver() {//from   w w w . j  ava2  s  .com
            setSearchTermStrategy(searchTermStrategy);
        }

        @Override
        protected Folder getFolder() {
            Folder folder = mock(Folder.class);
            given(folder.isOpen()).willReturn(true);
            try {
                given(folder.getMessages()).willReturn(!this.firstDone ? messages1 : messages2);
            } catch (MessagingException e) {
            }
            return folder;
        }

        @Override
        public Message[] receive() throws MessagingException {
            Message[] messages = searchForNewMessages();
            this.firstDone = true;
            return messages;
        }

    }
    ImapMailReceiver receiver = new TestReceiver();
    Message[] received = (Message[]) receiver.receive();
    assertEquals(1, received.length);
    assertSame(message1, received[0]);
    received = (Message[]) receiver.receive();
    assertEquals(1, received.length);
    assertSame(messages2, received);
    assertSame(message2, received[0]);
}

From source file:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java

public void generateMailNotification(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword, String notificationType, String fromFilter, String subjectFilter)
        throws Exception {
    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);//from   ww  w .j a  v  a2  s.  co m
    try {
        // connects to the message store
        Store store = session.getStore(mailStoreProtocol);
        store.connect(mailStoreHost, mailStoreUserName, mailStorePassword);

        logger.info("connected to message store");

        // opens the inbox folder
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_WRITE);

        // check if fromFilter is specified
        List<String> fromFilterList = null;

        if (StringUtils.isNotBlank(fromFilter)) {
            String[] fromFilterArray = StringUtils.split(fromFilter, "|");
            fromFilterList = Arrays.asList(fromFilterArray);
        }

        // check if subjectFilter is specified
        List<String> subjectFilterList = null;
        if (StringUtils.isNotBlank(subjectFilter)) {
            String[] subjectFilterArray = StringUtils.split(subjectFilter, "|");
            subjectFilterList = Arrays.asList(subjectFilterArray);
        }
        Map<String, Object> context = new HashMap<String, Object>();
        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();
        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String address = fromAddress[0].toString();
            String from = extractFromAddress(address);
            if (StringUtils.isBlank(from)) {
                logger.warn("From Address is not proper " + from);
                return;
            }
            boolean isValidFrom = isValidMatch(fromFilterList, from);

            // filter based on fromFilter specified
            if (null == fromFilterList || isValidFrom) {
                String subject = msg.getSubject();

                boolean isValidSubject = isValidMatch(subjectFilterList, subject);
                if (null == subjectFilterList || isValidSubject) {
                    String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
                    String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
                    String sentDate = msg.getSentDate().toString();

                    String messageContent = "";
                    try {
                        Object content = msg.getContent();
                        if (content != null) {
                            messageContent = content.toString();
                        }
                    } catch (Exception ex) {
                        messageContent = "[Error downloading content]";
                        ex.printStackTrace();
                    }
                    context.put("from", from);
                    context.put("to", toList);
                    context.put("cc", ccList);
                    context.put("subject", subject);
                    context.put("messagebody", messageContent);
                    context.put("sentdate", sentDate);

                    notificationController.createNotification(notificationType, context);
                    msg.setFlag(Flag.DELETED, true);
                } else {
                    logger.warn("subjectFilter doesn't match");
                }
            } else {
                logger.warn("this email originated from " + address
                        + " , which does not match fromAddress specified in the rule, it should be "
                        + fromFilter.toString());
            }
        }
        // disconnect and delete messages marked as DELETED
        folderInbox.close(true);
        store.close();
    } catch (NoSuchProviderException ex) {
        logger.warn("No provider for protocol: " + mailStoreProtocol + " " + ex);
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store" + ex);
    }
}

From source file:org.springframework.ws.transport.mail.monitor.AbstractMonitoringStrategy.java

/**
 * Retrieves new messages from the given folder. This implementation creates a {@link SearchTerm} that searches for
 * all messages in the folder that are {@link javax.mail.Flags.Flag#RECENT RECENT}, not {@link
 * javax.mail.Flags.Flag#ANSWERED ANSWERED}, and not {@link javax.mail.Flags.Flag#DELETED DELETED}. The search term
 * is used to {@link Folder#search(SearchTerm) search} for new messages.
 *
 * @param folder the folder to retrieve new messages from
 * @return the new messages/*from ww w . j a  v  a  2s . c  om*/
 * @throws MessagingException in case of JavaMail errors
 */
protected Message[] searchForNewMessages(Folder folder) throws MessagingException {
    if (!folder.isOpen()) {
        return new Message[0];
    }
    Flags supportedFlags = folder.getPermanentFlags();
    SearchTerm searchTerm = null;
    if (supportedFlags != null) {
        if (supportedFlags.contains(Flags.Flag.RECENT)) {
            searchTerm = new FlagTerm(new Flags(Flags.Flag.RECENT), true);
        }
        if (supportedFlags.contains(Flags.Flag.ANSWERED)) {
            FlagTerm answeredTerm = new FlagTerm(new Flags(Flags.Flag.ANSWERED), false);
            if (searchTerm == null) {
                searchTerm = answeredTerm;
            } else {
                searchTerm = new AndTerm(searchTerm, answeredTerm);
            }
        }
        if (supportedFlags.contains(Flags.Flag.DELETED)) {
            FlagTerm deletedTerm = new FlagTerm(new Flags(Flags.Flag.DELETED), false);
            if (searchTerm == null) {
                searchTerm = deletedTerm;
            } else {
                searchTerm = new AndTerm(searchTerm, deletedTerm);
            }
        }
    }
    return searchTerm != null ? folder.search(searchTerm) : folder.getMessages();
}

From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java

/**
 * {@inheritDoc}/*from ww  w.j  av a  2s.c  o  m*/
 * 
 * @see ch.entwine.weblounge.common.scheduler.JobWorker#execute(java.lang.String,
 *      java.util.Dictionary)
 */
public void execute(String name, Dictionary<String, Serializable> ctx) throws JobException {

    Site site = (Site) ctx.get(Site.class.getName());

    // Make sure the site is ready to accept content
    if (site.getContentRepository().isReadOnly()) {
        logger.warn("Unable to publish e-mail messages to site '{}': repository is read only", site);
        return;
    }

    WritableContentRepository repository = (WritableContentRepository) site.getContentRepository();

    // Extract the configuration from the job properties
    String provider = (String) ctx.get(OPT_PROVIDER);
    Account account = null;
    try {
        if (StringUtils.isBlank(provider)) {
            provider = DEFAULT_PROVIDER;
        }
        account = new Account(ctx);
    } catch (IllegalArgumentException e) {
        throw new JobException(this, e);
    }

    // Connect to the server
    Properties sessionProperties = new Properties();
    Session session = Session.getDefaultInstance(sessionProperties, null);
    Store store = null;
    Folder inbox = null;

    try {

        // Connect to the server
        try {
            store = session.getStore(provider);
            store.connect(account.getHost(), account.getLogin(), account.getPassword());
        } catch (NoSuchProviderException e) {
            throw new JobException(this, "Unable to connect using unknown e-mail provider '" + provider + "'",
                    e);
        } catch (MessagingException e) {
            throw new JobException(this, "Error connecting to " + provider + " account " + account, e);
        }

        // Open the account's inbox
        try {
            inbox = store.getFolder(INBOX);
            if (inbox == null)
                throw new JobException(this, "No inbox found at " + account);
            inbox.open(Folder.READ_WRITE);
        } catch (MessagingException e) {
            throw new JobException(this, "Error connecting to inbox at " + account, e);
        }

        // Get the messages from the server
        try {
            for (Message message : inbox.getMessages()) {
                if (!message.isSet(Flag.SEEN)) {
                    try {
                        Page page = aggregate(message, site);
                        message.setFlag(Flag.DELETED, true);
                        repository.put(page, true);
                        logger.info("E-Mail message published at {}", page.getURI());
                    } catch (Exception e) {
                        logger.info("E-Mail message discarded: {}", e.getMessage());
                        message.setFlag(Flag.SEEN, true);
                        // TODO: Reply to sender if the "from" field exists
                    }
                }
            }
        } catch (MessagingException e) {
            throw new JobException(this, "Error loading e-mail messages from inbox", e);
        }

        // Close the connection
        // but don't remove the messages from the server
    } finally {
        if (inbox != null) {
            try {
                inbox.close(true);
            } catch (MessagingException e) {
                throw new JobException(this, "Error closing inbox", e);
            }
        }
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                throw new JobException(this, "Error closing connection to e-mail server", e);
            }
        }
    }

}

From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java

/**
 * A method that executes the reading of data from the email account to the
 * RBNB server after all configuration of settings, connections to hosts,
 * and thread initiatizing occurs. This method contains the detailed code
 * for reading the data and interpreting the data files.
 *//*from   www  .  j ava 2 s  .c  o m*/
protected boolean execute() {
    logger.debug("StorXDispatcher.execute() called.");
    boolean failed = true; // indicates overall success of execute()
    boolean messageProcessed = false; // indicates per message success

    // declare the account properties that will be pulled from the
    // email.account.properties.xml file
    String accountName = "";
    String server = "";
    String username = "";
    String password = "";
    String protocol = "";
    String dataMailbox = "";
    String processedMailbox = "";
    String prefetch = "";

    // fetch data from each sensor in the account list
    List accountList = this.xmlConfiguration.getList("account.accountName");

    for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) {

        int aIndex = accountList.indexOf(aIterator.next());

        // populate the email connection variables from the xml properties
        // file
        accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName");
        server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server");
        username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username");
        password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password");
        protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol");
        dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox");
        processedMailbox = (String) this.xmlConfiguration
                .getProperty("account(" + aIndex + ").processedMailbox");
        prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch");

        logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName     : " + accountName + "\n"
                + "server          : " + server + "\n" + "username        : " + username + "\n"
                + "password        : " + password + "\n" + "protocol        : " + protocol + "\n"
                + "dataMailbox     : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n"
                + "prefetch        : " + prefetch + "\n");

        // get a connection to the mail server
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.imaps.partialfetch", prefetch);

        try {

            // create the imaps mail session
            this.mailSession = Session.getDefaultInstance(props, null);
            this.mailStore = mailSession.getStore(protocol);

        } catch (NoSuchProviderException nspe) {

            try {
                // pause for 10 seconds
                logger.debug(
                        "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry.");
                Thread.sleep(10000L);
                this.mailStore = mailSession.getStore(protocol);

            } catch (NoSuchProviderException nspe2) {

                logger.debug("There was an error connecting to the mail server. The " + "message was: "
                        + nspe2.getMessage());
                nspe2.printStackTrace();
                failed = true;
                return !failed;

            } catch (InterruptedException ie) {

                logger.debug("The thread was interrupted: " + ie.getMessage());
                failed = true;
                return !failed;

            }

        }

        try {

            this.mailStore.connect(server, username, password);

            // get folder references for the inbox and processed data box
            Folder inbox = mailStore.getFolder(dataMailbox);
            inbox.open(Folder.READ_WRITE);

            Folder processed = this.mailStore.getFolder(processedMailbox);
            processed.open(Folder.READ_WRITE);

            Message[] msgs;
            while (!inbox.isOpen()) {
                inbox.open(Folder.READ_WRITE);

            }
            msgs = inbox.getMessages();

            List<Message> messages = new ArrayList<Message>();
            Collections.addAll(messages, msgs);

            // sort the messages found in the inbox by date sent
            Collections.sort(messages, new Comparator<Message>() {

                public int compare(Message message1, Message message2) {
                    int value = 0;
                    try {
                        value = message1.getSentDate().compareTo(message2.getSentDate());
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                    return value;

                }

            });

            logger.debug("Number of messages: " + messages.size());
            for (Message message : messages) {

                // Copy the message to ensure we have the full attachment
                MimeMessage mimeMessage = (MimeMessage) message;
                MimeMessage copiedMessage = new MimeMessage(mimeMessage);

                // determine the sensor serial number for this message
                String messageSubject = copiedMessage.getSubject();
                Date sentDate = copiedMessage.getSentDate();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

                // The subfolder of the processed mail folder (e.g. 2016-12);
                String destinationFolder = formatter.format(sentDate);
                logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber());
                String[] subjectParts = messageSubject.split("\\s");
                String loggerSerialNumber = "SerialNumber";
                if (subjectParts.length > 1) {
                    loggerSerialNumber = subjectParts[2];

                }

                // Do we have a data attachment? If not, there's no data to
                // process
                if (copiedMessage.isMimeType("multipart/mixed")) {

                    logger.debug("Message size: " + copiedMessage.getSize());

                    MimeMessageParser parser = new MimeMessageParser(copiedMessage);
                    try {
                        parser.parse();

                    } catch (Exception e) {
                        logger.error("Failed to parse the MIME message: " + e.getMessage());
                        continue;
                    }
                    ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only

                    logger.debug("Has attachments: " + parser.hasAttachments());
                    for (DataSource dataSource : parser.getAttachmentList()) {
                        if (StringUtils.isNotBlank(dataSource.getName())) {
                            logger.debug(
                                    "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType());

                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            IOUtils.copy(dataSource.getInputStream(), outputStream);
                            messageAttachment = ByteBuffer.wrap(outputStream.toByteArray());

                        }
                    }

                    // We now have the attachment and serial number. Parse the attachment 
                    // for the data components, look up the storXSource based on the serial 
                    // number, and push the data to the DataTurbine

                    // parse the binary attachment
                    StorXParser storXParser = new StorXParser(messageAttachment);

                    // iterate through the parsed framesMap and handle each
                    // frame
                    // based on its instrument type
                    BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap();

                    Collection frameCollection = framesMap.getAll("/frames/frame");
                    Iterator framesIterator = frameCollection.iterator();

                    while (framesIterator.hasNext()) {

                        BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next();

                        // logger.debug(frameMap.toXMLString(1000));

                        String frameType = (String) frameMap.get("type");
                        String sensorSerialNumber = (String) frameMap.get("serialNumber");

                        // handle each instrument type
                        if (frameType.equals("HDR")) {
                            logger.debug("This is a header frame. Skipping it.");

                        } else if (frameType.equals("STX")) {

                            try {

                                // handle StorXSource
                                StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the StorXSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("SBE")) {

                            try {

                                // handle CTDSource
                                CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber);

                                // process the data using the CTDSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NLB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NDB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else {

                            logger.debug("The frame type " + frameType + " is not recognized. Skipping it.");
                        }

                    } // end while()

                    if (this.sourceMap.get(loggerSerialNumber) != null) {

                        // Note: Use message (not copiedMessage) when setting flags 

                        if (!messageProcessed) {
                            logger.info("Failed to process message: " + "Message Number: "
                                    + message.getMessageNumber() + "  " + "Logger Serial:"
                                    + loggerSerialNumber);
                            // leave it in the inbox, flagged as seen (read)
                            message.setFlag(Flags.Flag.SEEN, true);
                            logger.debug("Saw message " + message.getMessageNumber());

                        } else {

                            // message processed successfully. Create a by-month sub folder if it doesn't exist
                            // Copy the message and flag it deleted
                            Folder destination = processed.getFolder(destinationFolder);
                            boolean created = destination.create(Folder.HOLDS_MESSAGES);
                            inbox.copyMessages(new Message[] { message }, destination);
                            message.setFlag(Flags.Flag.DELETED, true);
                            logger.debug("Deleted message " + message.getMessageNumber());
                        } // end if()

                    } else {
                        logger.debug("There is no configuration information for " + "the logger serial number "
                                + loggerSerialNumber + ". Please add the configuration to the "
                                + "email.account.properties.xml configuration file.");

                    } // end if()

                } else {
                    logger.debug("This is not a data email since there is no "
                            + "attachment. Skipping it. Subject: " + messageSubject);

                } // end if()

            } // end for()

            // expunge messages and close the mail server store once we're
            // done
            inbox.expunge();
            this.mailStore.close();

        } catch (MessagingException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                failed = true;
                return !failed;

            }
            logger.info(
                    "There was an error reading the mail message. The " + "message was: " + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IOException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me3) {
                failed = true;
                return !failed;

            }
            logger.info("There was an I/O error reading the message part. The " + "message was: "
                    + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IllegalStateException ese) {
            try {
                this.mailStore.close();

            } catch (MessagingException me4) {
                failed = true;
                return !failed;

            }
            logger.info("There was an error reading messages from the folder. The " + "message was: "
                    + ese.getMessage());
            failed = true;
            return !failed;

        } finally {

            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                logger.debug("Couldn't close the mail store: " + me2.getMessage());

            }

        }

    }

    return !failed;
}

From source file:com.naryx.tagfusion.cfm.mail.cfPOP3.java

private void readMessages(cfSession _Session, Folder popFolder, cfQueryResultData popData, int _start, int _max,
        boolean GetAll, File attachmentDir) throws cfmRunTimeException {
    try {//  ww  w. j a  v  a  2s  . c  o  m
        int maxRows = _max;
        int startRow = _start;
        String messageNumber = getDynamic(_Session, "MESSAGENUMBER").getString();
        boolean containsUID = containsAttribute("UID");
        boolean usingMessageNumber = messageNumber.length() > 0;
        int msgCount = popFolder.getMessageCount();

        // if MAXROWS is not specified, or UID or MESSAGENUMBER is, then we want to get all the messages
        if (_max == -1 || containsUID || usingMessageNumber) {
            maxRows = msgCount;
        }
        if (containsUID || usingMessageNumber) {
            startRow = 1;
        }

        if (msgCount != 0 && startRow > msgCount) {
            throw newRunTimeException(
                    "The value of STARTROW must not be greater than the total number of messages in the folder, "
                            + popFolder.getMessageCount() + ".");
        }

        Message[] listOfMessages;
        if (!usingMessageNumber) {
            listOfMessages = popFolder.getMessages();
        } else {
            listOfMessages = popFolder.getMessages(getMessageList(messageNumber));
        }

        FetchProfile fProfile = new FetchProfile();
        fProfile.add(FetchProfile.Item.ENVELOPE);
        fProfile.add(UIDFolder.FetchProfileItem.UID);
        popFolder.fetch(listOfMessages, fProfile);

        if (containsUID) {
            String[] messageUIDList = getMessageUIDList(getDynamic(_Session, "UID").getString());

            for (int x = 0; x < listOfMessages.length; x++) {
                if (messageUIDList.length == 0
                        || messageUIDValid(messageUIDList, getMessageUID(popFolder, listOfMessages[x]))) {
                    populateMessage(_Session, listOfMessages[x], popData, GetAll, attachmentDir, popFolder);
                }
            }
        } else {
            popFolder.fetch(listOfMessages, fProfile);
            int end = startRow - 1 + maxRows;
            if (end > listOfMessages.length) {
                end = listOfMessages.length;
            }
            for (int x = startRow - 1; x < end; x++) {
                populateMessage(_Session, listOfMessages[x], popData, GetAll, attachmentDir, popFolder);
            }
        }
    } catch (Exception E) {
        if (E.getMessage() != null)
            throw newRunTimeException(E.getMessage());
        else
            throw newRunTimeException(E.toString());
    }

}

From source file:com.liferay.mail.imap.IMAPAccessor.java

public void storeEnvelopes(long folderId, boolean allMessages) throws PortalException {

    Folder jxFolder = null;

    try {//from  ww w. j a  v a  2  s.c om
        com.liferay.mail.model.Folder folder = FolderLocalServiceUtil.fetchFolder(folderId);

        if (folder == null) {
            return;
        }

        jxFolder = openFolder(folderId);

        int messageCount = jxFolder.getMessageCount();

        FolderLocalServiceUtil.updateFolder(folderId, folder.getFullName(), folder.getDisplayName(),
                messageCount);

        if (messageCount == 0) {
            return;
        }

        Message oldestJxMessage = getMessage(folderId, jxFolder, true);
        Message newestJxMessage = getMessage(folderId, jxFolder, false);

        Message[] jxMessages = new Message[0];

        if (allMessages) {
            if (_log.isDebugEnabled()) {
                _log.debug("Downloading all messages from folder " + jxFolder.getFullName());
            }

            jxMessages = jxFolder.getMessages();
        } else if ((oldestJxMessage == null) && (newestJxMessage == null)) {
            if (_log.isDebugEnabled()) {
                _log.debug(
                        "Downloading messages from folder " + jxFolder.getFullName() + " for the first time");
            }

            int startingMessageNumber = messageCount - PortletPropsValues.MESSAGES_SYNC_COUNT;

            if (startingMessageNumber < 1) {
                startingMessageNumber = 1;
            }

            jxMessages = jxFolder.getMessages(startingMessageNumber, messageCount);
        } else {
            int oldestMessageNumber = oldestJxMessage.getMessageNumber();
            int newestMessageNumber = newestJxMessage.getMessageNumber();

            if (newestMessageNumber != messageCount) {
                if (_log.isDebugEnabled()) {
                    _log.debug("Downloading new messages from folder " + jxFolder.getFullName());
                }

                jxMessages = jxFolder.getMessages(newestMessageNumber + 1, messageCount);
            } else if (oldestMessageNumber != 1) {
                if (_log.isDebugEnabled()) {
                    _log.debug("Downloading old messages from folder " + jxFolder.getFullName());
                }

                int startingMessageNumber = oldestMessageNumber - PortletPropsValues.MESSAGES_SYNC_COUNT;

                if (startingMessageNumber < 1) {
                    startingMessageNumber = 1;
                }

                jxMessages = jxFolder.getMessages(startingMessageNumber, oldestMessageNumber - 1);
            }
        }

        storeEnvelopes(folderId, jxFolder, jxMessages);
    } catch (MessagingException me) {
        throw new MailException(me);
    } finally {
        closeFolder(jxFolder, false);
    }
}