Example usage for javax.mail Folder READ_WRITE

List of usage examples for javax.mail Folder READ_WRITE

Introduction

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

Prototype

int READ_WRITE

To view the source code for javax.mail Folder READ_WRITE.

Click Source Link

Document

The state and contents of this folder can be modified.

Usage

From source file:br.unicamp.cotuca.dpd.pd12.acinet.vagalmail.servlet.Configuracoes.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    if (request.getRequestURI().contains("/pasta")) {
        String acao = request.getParameter("acao"), url = request.getParameter("url"),
                novo = request.getParameter("novo");

        JSONObject obj = new JSONObject();
        if (acao == null || url == null) {
            obj.put("erro", "Solicitao invlida");
            obj.writeJSONString(response.getWriter());
            return;
        }// w  w  w .java 2s.c om

        if ((acao.equals("renomear") || acao.equals("nova")) && novo == null) {
            obj.put("erro", "Solicitao invlida");
            obj.writeJSONString(response.getWriter());
            return;
        }

        try {
            Conta conta = (Conta) request.getSession().getAttribute("conta");
            Store store = Logar.getImapStore(conta);

            Folder pasta = null;

            if (!acao.equals("nova")) {
                URLName urln = new URLName(url);
                pasta = store.getFolder(urln);

                if (pasta.isOpen())
                    pasta.close(false);
            }

            switch (acao) {
            case "renomear":
                if (pasta.renameTo(store.getFolder(novo))) {
                    obj.put("sucesso", "Renomeado com sucesso");
                } else {
                    obj.put("erro", "Erro ao renomear a pasta");
                }
                break;
            case "esvaziar":
                pasta.open(Folder.READ_WRITE);
                pasta.setFlags(1, pasta.getMessageCount(), new Flags(Flags.Flag.DELETED), true);
                pasta.expunge();
                obj.put("sucesso", "Esvaziado com sucesso");
                break;
            case "excluir":
                if (pasta.delete(true)) {
                    obj.put("sucesso", "Excludo com sucesso");
                } else {
                    obj.put("erro", "Erro ao excluir a pasta");
                }
                break;
            case "nova":
                pasta = store.getFolder(novo);
                if (!pasta.exists()) {
                    if (pasta.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)) {
                        obj.put("sucesso", "Criado com sucesso");
                    } else {
                        obj.put("erro", "Erro ao criar a pasta");
                    }
                } else {
                    obj.put("erro", "Erro ao criar a pasta");
                }
                break;
            }
        } catch (MessagingException ex) {
            obj.put("erro", "Erro ao processar solicitao");
        }

        obj.writeJSONString(response.getWriter());

        return;
    }

    String metodo = request.getParameter("acao");
    if (metodo == null) {
        return;
    } else if (metodo.equals("nova")) {
        EntityManager em = BD.getEntityManager();

        try {
            em.getTransaction().begin();

            Login usuario = Logar.getLogin(request.getSession());

            Conta conta = new Conta();
            conta.setEmail(request.getParameter("email"));
            conta.setImapHost(request.getParameter("imapHost"));
            conta.setImapPort(Integer.parseInt(request.getParameter("imapPort")));
            conta.setImapPassword(request.getParameter("imapPassword"));
            conta.setImapUser(request.getParameter("imapLogin"));
            conta.setSmtpHost(request.getParameter("smtpHost"));
            conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort")));
            conta.setSmtpPassword(request.getParameter("smtpPassword"));
            conta.setSmtpUser(request.getParameter("smtpLogin"));
            conta.setIdLogin(usuario);

            em.persist(conta);
            em.merge(usuario);

            em.getTransaction().commit();
            em.refresh(conta);
            em.refresh(usuario);

            request.setAttribute("mensagem", "sucesso");
        } catch (Logar.NaoAutenticadoException | PersistenceException ex) {
            em.getTransaction().rollback();

            request.setAttribute("mensagem", "erro");
        }

        request.getRequestDispatcher("/conf.jsp?metodo=nova").forward(request, response);
    } else if (metodo.equals("conta")) {
        EntityManager em = BD.getEntityManager();

        try {
            em.getTransaction().begin();

            Conta conta = (Conta) request.getSession().getAttribute("conta");

            em.refresh(conta);
            conta.setEmail(request.getParameter("email"));
            conta.setImapHost(request.getParameter("imapHost"));
            conta.setImapPort(Integer.parseInt(request.getParameter("imapPort")));
            conta.setImapPassword(request.getParameter("imapPassword"));
            conta.setImapUser(request.getParameter("imapLogin"));
            conta.setSmtpHost(request.getParameter("smtpHost"));
            conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort")));
            conta.setSmtpPassword(request.getParameter("smtpPassword"));
            conta.setSmtpUser(request.getParameter("smtpLogin"));

            em.getTransaction().commit();

            request.setAttribute("mensagem", "sucesso");
        } catch (PersistenceException ex) {
            em.getTransaction().rollback();

            request.setAttribute("mensagem", "erro");
        }

        request.getRequestDispatcher("/conf.jsp?metodo=conta").forward(request, response);

    } else if (metodo.equals("senha")) {
        EntityManager em = BD.getEntityManager();

        try {

            Login usuario = Logar.getLogin(request.getSession());

            em.refresh(usuario);

            String senatu = request.getParameter("senAtu"), novasen = request.getParameter("senNova"),
                    novasen2 = request.getParameter("senNova2");

            if (novasen.equals(novasen2) && senatu.equals(usuario.getSenha())) {

                em.getTransaction().begin();

                usuario.setSenha(novasen);

                em.getTransaction().commit();

                request.setAttribute("mensagem", "sucesso");
            } else {
                if (!novasen.equals(novasen2))
                    request.setAttribute("mensagem", "senneq");
                else
                    request.setAttribute("mensagem", "antsen");
            }
        } catch (Logar.NaoAutenticadoException | PersistenceException ex) {
            em.getTransaction().rollback();

            request.setAttribute("mensagem", "erro");
        }

        request.getRequestDispatcher("/conf.jsp?metodo=senha").forward(request, response);

    }
}

From source file:org.accesointeligente.server.robots.ResponseChecker.java

public void connectAndCheck() {
    if (ApplicationProperties.getProperty("email.server") == null
            || ApplicationProperties.getProperty("email.user") == null
            || ApplicationProperties.getProperty("email.password") == null
            || ApplicationProperties.getProperty("email.folder") == null
            || ApplicationProperties.getProperty("email.failfolder") == null
            || ApplicationProperties.getProperty("attachment.directory") == null
            || ApplicationProperties.getProperty("attachment.baseurl") == null) {
        logger.error("Properties are not defined!");
        return;//from  w w  w  .  j  a  va  2  s.c  o  m
    }

    org.hibernate.Session hibernate = null;

    try {
        session = Session.getInstance(props, null);
        store = session.getStore("imaps");
        store.connect(ApplicationProperties.getProperty("email.server"),
                ApplicationProperties.getProperty("email.user"),
                ApplicationProperties.getProperty("email.password"));

        Folder failbox = store.getFolder(ApplicationProperties.getProperty("email.failfolder"));
        Folder inbox = store.getFolder(ApplicationProperties.getProperty("email.folder"));
        inbox.open(Folder.READ_WRITE);

        for (Message message : inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false))) {
            try {
                logger.info("Sender: " + message.getFrom()[0] + "\tSubject: " + message.getSubject());
                remoteIdentifiers = null;
                messageBody = null;
                remoteIdentifiers = new HashSet<String>();

                if (message.getSubject() != null) {
                    Matcher matcher = pattern.matcher(message.getSubject());

                    if (matcher.matches()) {
                        remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2),
                                Integer.parseInt(matcher.group(3))));
                        logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2),
                                Integer.parseInt(matcher.group(3))));
                    }
                }

                Object content = message.getContent();

                if (content instanceof Multipart) {
                    Multipart mp = (Multipart) message.getContent();
                    logger.info("Email content type is Multipart, each part of " + mp.getCount()
                            + " will be processed");

                    for (int i = 0, n = mp.getCount(); i < n; i++) {
                        Part part = mp.getBodyPart(i);
                        logger.info("Part: " + (i + 1) + " of " + mp.getCount());
                        processPart(part);
                    }
                } else if (content instanceof String) {
                    logger.info("Email content type is String");
                    messageBody = (String) content;
                    Matcher matcher;
                    StringTokenizer tokenizer = new StringTokenizer(messageBody);

                    while (tokenizer.hasMoreTokens()) {
                        String token = tokenizer.nextToken();
                        matcher = pattern.matcher(token);

                        if (matcher.matches()) {
                            remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2),
                                    Integer.parseInt(matcher.group(3))));
                            logger.info("remote identifier: " + formatIdentifier(matcher.group(1),
                                    matcher.group(2), Integer.parseInt(matcher.group(3))));
                        }
                    }
                } else {
                    logger.info("Email content type isn't String or Multipart");
                    message.setFlag(Flag.SEEN, false);
                    inbox.copyMessages(new Message[] { message }, failbox);
                    message.setFlag(Flag.DELETED, true);
                    inbox.expunge();
                    continue;
                }

                Boolean requestFound = false;
                Matcher matcher = htmlPattern.matcher(messageBody);

                if (matcher.find()) {
                    messageBody = htmlToString(messageBody);
                }

                logger.info("Searching for Request Remote Identifier");
                for (String remoteIdentifier : remoteIdentifiers) {
                    hibernate = HibernateUtil.getSession();
                    hibernate.beginTransaction();

                    Criteria criteria = hibernate.createCriteria(Request.class);
                    criteria.add(Restrictions.eq("remoteIdentifier", remoteIdentifier));
                    Request request = (Request) criteria.uniqueResult();
                    hibernate.getTransaction().commit();

                    if (request != null) {
                        logger.info("Request found for Remote Identifier: " + remoteIdentifier);
                        Response response;

                        // If the attachments haven't been used, use them. Otherwise, copy them.
                        if (!requestFound) {
                            response = createResponse(message.getFrom()[0].toString(), message.getSentDate(),
                                    message.getSubject(), messageBody);
                        } else {
                            response = createResponse(message.getFrom()[0].toString(), message.getSentDate(),
                                    message.getSubject(), messageBody);
                        }

                        hibernate = HibernateUtil.getSession();
                        hibernate.beginTransaction();

                        response.setRequest(request);
                        request.setStatus(RequestStatus.RESPONDED);
                        request.setExpired(RequestExpireType.WITHRESPONSE);
                        request.setResponseDate(new Date());
                        hibernate.update(request);
                        hibernate.update(response);
                        hibernate.getTransaction().commit();
                        requestFound = true;
                    }
                }

                if (!requestFound) {
                    logger.info("Request not found");
                    createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(),
                            messageBody);
                    message.setFlag(Flag.SEEN, false);
                    inbox.copyMessages(new Message[] { message }, failbox);
                    message.setFlag(Flag.DELETED, true);
                    inbox.expunge();
                }
            } catch (Exception e) {
                if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
                    hibernate.getTransaction().rollback();
                }

                logger.error(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
            hibernate.getTransaction().rollback();
        }

        logger.error(e.getMessage(), e);
    }
}

From source file:org.apache.camel.component.mail.MailConsumer.java

protected int poll() throws Exception {
    // must reset for each poll
    shutdownRunningTask = null;//from w ww .jav  a  2 s .com
    pendingExchanges = 0;
    int polledMessages = 0;

    ensureIsConnected();

    if (store == null || folder == null) {
        throw new IllegalStateException("MailConsumer did not connect properly to the MailStore: "
                + getEndpoint().getConfiguration().getMailStoreLogInformation());
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Polling mailfolder: " + getEndpoint().getConfiguration().getMailStoreLogInformation());
    }

    if (getEndpoint().getConfiguration().getFetchSize() == 0) {
        LOG.warn(
                "Fetch size is 0 meaning the configuration is set to poll no new messages at all. Camel will skip this poll.");
        return 0;
    }

    // ensure folder is open
    if (!folder.isOpen()) {
        folder.open(Folder.READ_WRITE);
    }

    try {
        int count = folder.getMessageCount();
        if (count > 0) {
            Message[] messages;

            // should we process all messages or only unseen messages
            if (getEndpoint().getConfiguration().isUnseen()) {
                messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
            } else {
                messages = folder.getMessages();
            }

            polledMessages = processBatch(CastUtils.cast(createExchanges(messages)));
        } else if (count == -1) {
            throw new MessagingException("Folder: " + folder.getFullName() + " is closed");
        }
    } catch (Exception e) {
        handleException(e);
    } finally {
        // need to ensure we release resources
        try {
            if (folder.isOpen()) {
                folder.close(true);
            }
        } catch (Exception e) {
            // some mail servers will lock the folder so we ignore in this case (CAMEL-1263)
            LOG.debug("Could not close mailbox folder: " + folder.getName(), e);
        }
    }

    return polledMessages;
}

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

/**
 * Move messages from the parent backlog folder to year-month folders based
 * on the date sent of the message// ww  w . j a va 2 s . c  o  m
 * 
 * @param targetMailbox 
 * @param sourceMailbox 
 */
public static void organizeMessages(String sourceMailbox, String targetMailbox) {
    ArrayList<String> years = getYears();
    ArrayList<String> months = getMonths();

    try {
        targetParentFolder = mailStore.getFolder(targetMailbox);
        targetParentFolder.open(Folder.READ_WRITE);
        log.debug("Target folder: " + targetParentFolder.getName());

        sourceParentFolder = mailStore.getFolder(sourceMailbox);
        sourceParentFolder.open(Folder.READ_WRITE);
        log.debug("Source folder: " + sourceParentFolder.getName());

        Message messages[];
        while (!targetParentFolder.isOpen()) {
            targetParentFolder.open(Folder.READ_WRITE);

        }
        messages = (Message[]) sourceParentFolder.getMessages();
        log.debug("Processing " + messages.length + " messages.");

        int count = 0;
        for (Message message : messages) {
            Date sentDate = message.getSentDate();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
            String folderByDate = formatter.format(sentDate);

            Folder destinationFolder = targetParentFolder.getFolder(folderByDate);
            targetParentFolder.copyMessages(new Message[] { message }, destinationFolder);
            //message.setFlag(Flags.Flag.DELETED, true);
            count++;
            log.debug(count + ")" + message.getSentDate() + " moved to\t" + destinationFolder.getFullName());
        }

    } catch (MessagingException e) {
        e.printStackTrace();

    } finally {
        try {
            mailStore.close();

        } catch (MessagingException e) {
            e.printStackTrace();

        }
    }

}

From source file:com.yfiton.notifiers.email.EmailNotifierTest.java

private boolean checkEmailReception(String subject, String host, String username, String password)
        throws MessagingException {
    Properties properties = new Properties();
    properties.put("mail.store.protocol", "imaps");
    Session session = Session.getInstance(properties);

    Store store = null;// ww w  .j a  v a 2  s  .co  m

    try {
        store = session.getStore("imaps");
        store.connect(host, username, password);

        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);

        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if (message.getSubject().equals(subject)) {
                message.setFlag(Flags.Flag.DELETED, true);
                return true;
            }
        }

        inbox.close(true);
    } finally {
        try {
            if (store != null) {
                store.close();
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    return false;
}

From source file:org.apache.axis2.transport.mail.MailRequestResponseClient.java

private Message getMessage(String requestMsgId) throws Exception {
    MimeMessage response = null;//ww  w  . j  a va 2  s .c om
    Folder folder = store.getFolder(MailConstants.DEFAULT_FOLDER);
    folder.open(Folder.READ_WRITE);
    Message[] msgs = folder.getMessages();
    log.debug(msgs.length + " messages in mailbox");
    loop: for (Message m : msgs) {
        MimeMessage mimeMessage = (MimeMessage) m;
        String[] inReplyTo = mimeMessage.getHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO);
        log.debug("Found message " + mimeMessage.getMessageID() + " in reply to " + Arrays.toString(inReplyTo));
        if (inReplyTo != null && inReplyTo.length > 0) {
            for (int j = 0; j < inReplyTo.length; j++) {
                if (requestMsgId.equals(inReplyTo[j])) {
                    log.debug("Identified message " + mimeMessage.getMessageID() + " as the response to "
                            + requestMsgId + "; retrieving it from the store");
                    // We need to create a copy so that we can delete the original and close the folder
                    response = new MimeMessage(mimeMessage);
                    log.debug("Flagging message " + mimeMessage.getMessageID() + " for deletion");
                    mimeMessage.setFlag(Flags.Flag.DELETED, true);
                    break loop;
                }
            }
        }
        log.warn("Don't know what to do with message " + mimeMessage.getMessageID() + "; skipping");
    }
    folder.close(true);
    return response;
}

From source file:org.wso2.esb.integration.common.utils.MailToTransportUtil.java

/**
 * Check a particular email has received to a given email folder by email subject.
 *
 * @param emailSubject - Email emailSubject to find email is in inbox or not
 * @return - found the email or not//from  www.ja va 2  s . co m
 * @throws ESBMailTransportIntegrationTestException - Is thrown if an error occurred while reading the emails
 */
public static boolean isMailReceivedBySubject(String emailSubject, String folder)
        throws ESBMailTransportIntegrationTestException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection();
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the email emailSubject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
        return emailReceived;
    } catch (MessagingException ex) {
        log.error("Error when getting mail count ", ex);
        throw new ESBMailTransportIntegrationTestException("Error when getting mail count ", ex);
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                log.warn("Error when closing the store ", e);
            }
        }
    }
}

From source file:org.campware.dream.modules.scheduledjobs.Pop3Job.java

private void doReceiveMessages() throws Exception {

    String host = TurbineResources.getString("mail.pop3.host");
    String username = TurbineResources.getString("mail.pop3.user");
    String password = TurbineResources.getString("mail.pop3.password");

    // Create empty properties
    Properties props = new Properties();

    // Get session
    Session session = Session.getDefaultInstance(props, null);

    // Get the store
    Store store = session.getStore("pop3");

    // Connect to store
    store.connect(host, username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");

    // Open read-only
    folder.open(Folder.READ_WRITE);

    // Get attributes & flags for all messages
    ////from  w w  w  .  jav  a2 s.  co  m
    Message[] messages = folder.getMessages();
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);
    fp.add(FetchProfile.Item.FLAGS);
    fp.add("X-Mailer");
    folder.fetch(messages, fp);

    // Process each message
    //
    Address fromAddress = new InternetAddress();
    String from = new String();
    String name = new String();
    String email = new String();
    String subject = new String();
    String content = new String();
    for (int i = 0; i < messages.length; i++) {
        email = ((InternetAddress) messages[i].getFrom()[0]).getAddress();
        name = ((InternetAddress) messages[i].getFrom()[0]).getPersonal();
        subject = messages[i].getSubject();
        content = messages[i].getContent().toString();

        DinboxEvent entry = new DinboxEvent();

        Criteria criteria = new Criteria();
        criteria.add(DistributorPeer.EMAIL, (Object) email, Criteria.EQUAL);
        if (DistributorPeer.doSelect(criteria).size() > 0) {
            Distributor myDistrib = (Distributor) DistributorPeer.doSelect(criteria).get(0);
            entry.setDistributorId(myDistrib.getDistributorId());
        } else {
            if (name != null) {
                entry.setBody("From: " + name + " " + email + "\n\n" + content);
            } else {
                entry.setBody("From: " + email + "\n\n" + content);
            }
        }

        entry.setDinboxEventCode(getTempCode());

        entry.setEventType(10);
        entry.setEventChannel(10);
        entry.setSubject(subject);

        entry.setIssuedDate(new Date());
        entry.setCreatedBy("scheduler");
        entry.setCreated(new Date());
        entry.setModifiedBy("scheduler");
        entry.setModified(new Date());

        Connection conn = Transaction.begin(DinboxEventPeer.DATABASE_NAME);
        boolean success = false;
        try {
            entry.save(conn);
            entry.setDinboxEventCode(getRowCode("IE", entry.getDinboxEventId()));
            entry.save(conn);
            Transaction.commit(conn);
            success = true;

        } finally {
            if (!success)
                Transaction.safeRollback(conn);
        }

        messages[i].setFlag(Flags.Flag.DELETED, true);
    }

    // Close connection 
    folder.close(true);
    store.close();

}

From source file:com.cubusmail.mail.imap.IMAPMailFolder.java

public Message[] retrieveMessages(String sortfield) {

    Message[] msgs = EMPTY_MESSAGE_ARRAY;
    if (this.folder != null) {
        try {/* w  ww  .j a v  a  2 s  .  co  m*/
            if (!this.folder.isOpen()) {
                this.folder.open(Folder.READ_WRITE);
            }

            long time = System.currentTimeMillis();
            logger.debug("Start getting messages...");
            msgs = folder.getMessages();
            logger.debug(
                    "Millis for getting " + msgs.length + " messages: " + (System.currentTimeMillis() - time));
            time = System.currentTimeMillis();
            FetchProfile fp = MessageUtils.createFetchProfile(false, sortfield);

            logger.debug("Start fetching messages...");
            folder.fetch(msgs, fp);
            logger.debug(
                    "Millis for fetching " + msgs.length + " Messages: " + (System.currentTimeMillis() - time));

        } catch (MessagingException e) {
            logger.error(e.getMessage(), e);
        }
    }

    return msgs;
}

From source file:org.xwiki.contrib.mail.internal.DefaultMailReader.java

/**
 * {@inheritDoc}//w  w  w  .  j  a  v  a 2 s  .  c om
 * 
 * @throws MessagingException
 * @throws
 * @throws Exception
 * @see org.xwiki.contrib.mail.IMailReader#read(java.lang.String, int, java.lang.String, java.lang.String,
 *      java.lang.String, java.lang.String, boolean, int)
 */
@Override
public List<Message> read(final String folder, final boolean onlyUnread, final int max)
        throws MessagingException {
    assert (getMailSource() != null);
    assert (getMailSource().getHostname() != null);

    store = null;
    List<Message> messages = new ArrayList<Message>();
    boolean isGmail = getMailSource().getHostname() != null
            && getMailSource().getHostname().endsWith(".gmail.com");

    logger.info("Trying to retrieve mails from server " + getMailSource().getHostname());

    this.session = createSession(getMailSource().getProtocol(), getMailSource().getAdditionalProperties(),
            isGmail, getMailSource().isAutoTrustSSLCertificates());

    // Get a Store object
    store = session.getStore();

    // Connect to the mail account
    store.connect(getMailSource().getHostname(), getMailSource().getPort(), getMailSource().getUsername(),
            getMailSource().getPassword());
    Folder fldr;
    // Specifically for GMAIL ...
    if (isGmail) {
        fldr = store.getDefaultFolder();
    }
    fldr = store.getFolder(folder);

    fldr.open(Folder.READ_WRITE);

    Message[] msgsArray;
    // Searches for mails not already read
    if (onlyUnread) {
        FlagTerm searchterms = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        msgsArray = fldr.search(searchterms);
    } else {
        msgsArray = fldr.getMessages();
    }

    if (max > 0 && msgsArray.length > max) {
        msgsArray = (Message[]) ArrayUtils.subarray(msgsArray, 0, max);
    }
    messages = new ArrayList<Message>(Arrays.asList(msgsArray));

    logger.info("Found " + messages.size() + " messages");

    // Note: we leave the Store opened to allow reading returned Messages

    return messages;
}