Example usage for javax.mail Store getFolder

List of usage examples for javax.mail Store getFolder

Introduction

In this page you can find the example usage for javax.mail Store getFolder.

Prototype

public abstract Folder getFolder(URLName url) throws MessagingException;

Source Link

Document

Return a closed Folder object, corresponding to the given URLName.

Usage

From source file:de.saly.elasticsearch.importer.imap.mailsource.ParallelPollingIMAPMailSource.java

private ProcessResult processMessageSlice(final int start, final int end, final String folderName)
        throws Exception {

    logger.debug("processMessageSlice() started with " + start + "/" + end + "/" + folderName);
    final long startTime = System.currentTimeMillis();
    final Store store = Session.getInstance(props).getStore();
    store.connect(user, password);/*from  w  ww.j  a  va2  s . c  o m*/
    final Folder folder = store.getFolder(folderName);
    final UIDFolder uidfolder = (UIDFolder) folder;

    IMAPUtils.open(folder);

    try {

        final Message[] msgs = folder.getMessages(start, end);
        folder.fetch(msgs, IMAPUtils.FETCH_PROFILE_HEAD);

        logger.debug("folder fetch done");

        long highestUid = 0;
        int processedCount = 0;

        for (final Message m : msgs) {
            try {

                IMAPUtils.open(folder);
                final long uid = uidfolder.getUID(m);

                mailDestination.onMessage(m);

                highestUid = Math.max(highestUid, uid);
                processedCount++;

                if (Thread.currentThread().isInterrupted()) {
                    break;
                }

            } catch (final Exception e) {
                stateManager.onError("Unable to make indexable message", m, e);
                logger.error("Unable to make indexable message due to {}", e, e.toString());

                IMAPUtils.open(folder);
            }
        }

        final long endTime = System.currentTimeMillis() + 1;
        final ProcessResult pr = new ProcessResult(highestUid, processedCount, endTime - startTime);
        logger.debug("processMessageSlice() ended with " + pr);
        return pr;

    } finally {

        IMAPUtils.close(folder);
        IMAPUtils.close(store);
    }

}

From source file:org.apache.syncope.core.logic.NotificationTest.java

private boolean verifyMail(final String sender, final String subject) throws Exception {
    LOG.info("Waiting for notification to be sent...");
    try {/* ww w .  jav a2s  . co m*/
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    }

    boolean found = false;
    Session session = Session.getDefaultInstance(System.getProperties());
    Store store = session.getStore("pop3");
    store.connect(POP3_HOST, POP3_PORT, MAIL_ADDRESS, MAIL_PASSWORD);

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

    Message[] messages = inbox.getMessages();
    for (int i = 0; i < messages.length; i++) {
        if (sender.equals(messages[i].getFrom()[0].toString()) && subject.equals(messages[i].getSubject())) {
            found = true;
            messages[i].setFlag(Flag.DELETED, true);
        }
    }

    inbox.close(true);
    store.close();
    return found;
}

From source file:jp.mamesoft.mailsocketchat.Mail.java

public void run() {
    while (true) {
        try {//from  ww  w.j  a v a 2  s.  com
            System.out.println("????");
            Properties props = System.getProperties();

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

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

            // Connect
            store.connect("imap.gmail.com", 993, Mailsocketchat.mail_user, Mailsocketchat.mail_pass);
            System.out.println("??????");

            // Open a Folder
            Folder folder = store.getFolder("INBOX");
            if (folder == null || !folder.exists()) {
                System.out.println("IMAP??????");
                System.exit(1);
            }

            folder.open(Folder.READ_WRITE);

            // Add messageCountListener to listen for new messages
            folder.addMessageCountListener(new MessageCountAdapter() {
                public void messagesAdded(MessageCountEvent ev) {
                    Message[] msgs = ev.getMessages();

                    // Just dump out the new messages
                    for (int i = 0; i < msgs.length; i++) {
                        try {
                            System.out.println("?????");
                            InternetAddress addrfrom = (InternetAddress) msgs[i].getFrom()[0];
                            String subject = msgs[i].getSubject();
                            if (subject == null) {
                                subject = "";
                            }

                            Pattern hashtag_p = Pattern.compile("#(.+)");
                            Matcher hashtag_m = hashtag_p.matcher(subject);

                            if (subject.equals("#")) {
                                hashtag = null;
                            } else if (hashtag_m.find()) {
                                hashtag = hashtag_m.group(1);
                            }

                            String comment = msgs[i].getContent().toString().replaceAll("\r\n", " ");
                            comment = comment.replaceAll("\n", " ");
                            comment = comment.replaceAll("\r", " ");
                            JSONObject data = new JSONObject();
                            data.put("comment", comment);
                            if (hashtag != null) {
                                data.put("channel", hashtag);
                            }
                            if (!comment.equals("") && !comment.equals(" ") && !comment.equals("  ")) {
                                Mailsocketchat.socket.emit("say", data);
                                System.out.println("????");
                            }

                            //
                            if (subject.equals("push") || subject.equals("Push")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 2);
                                Mailsocketchat.push = true;
                                Mailsocketchat.repeat = false;
                                Mailsocketchat.address = addrfrom.getAddress();
                                repeatthread.cancel();
                                repeatthread = null;
                                System.out.println("?????");
                            } else if (subject.equals("fetch") || subject.equals("Fetch")
                                    || subject.equals("?")) {
                                Send(addrfrom.getAddress(), 3);
                                Mailsocketchat.push = false;
                                Mailsocketchat.repeat = false;
                                repeatthread.cancel();
                                repeatthread = null;
                                System.out.println("??????");
                            } else if (subject.equals("repeat") || subject.equals("Repeat")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 7);
                                Mailsocketchat.push = false;
                                Mailsocketchat.repeat = true;
                                Mailsocketchat.address = addrfrom.getAddress();
                                if (repeatthread == null) {
                                    repeatthread = new Repeat();
                                    repeat = new Timer();
                                }
                                repeat.schedule(repeatthread, 0, 30 * 1000);
                                System.out.println("?????");
                            } else if (subject.equals("list") || subject.equals("List")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 4);
                            } else if (subject.equals("help") || subject.equals("Help")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 5);
                            } else {
                                if (!Mailsocketchat.push && !Mailsocketchat.repeat) {
                                    Send(addrfrom.getAddress(), 0);
                                } else if (comment.equals("") || comment.equals(" ") || comment.equals("  ")) {
                                    Send(addrfrom.getAddress(), 5);
                                }
                            }
                        } catch (IOException ioex) {
                            System.out.println(
                                    "??????????");
                        } catch (MessagingException mex) {
                            System.out.println(
                                    "??????????");
                        }
                    }
                }
            });

            // Check mail once in "freq" MILLIseconds
            int freq = 1000; //??
            boolean supportsIdle = false;
            try {
                if (folder instanceof IMAPFolder) {
                    IMAPFolder f = (IMAPFolder) folder;
                    f.idle();
                    supportsIdle = true;
                }
            } catch (FolderClosedException fex) {
                throw fex;
            } catch (MessagingException mex) {
                supportsIdle = false;
            }
            for (;;) {
                if (supportsIdle && folder instanceof IMAPFolder) {
                    IMAPFolder f = (IMAPFolder) folder;
                    f.idle();
                } else {
                    Thread.sleep(freq); // sleep for freq milliseconds

                    // This is to force the IMAP server to send us
                    // EXISTS notifications. 
                    folder.getMessageCount();
                }
            }

        } catch (Exception ex) {
            System.out.println("??????????");
        }
    }
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
* Return the {@link Folder} object corresponding to the given 
* {@link ImapGmailLabel} name. /*from   w  w  w.jav a 2 s.  co m*/
* Note that a {@link Folder} object is returned only if the named 
* {@link Folder} physically exist on the Store.
* 
* @param name the name of the folder
* @param store instance of Gmail {@link Store}
*/
private Folder getFolder(String name, final Store store) {
    if (store == null) {
        throw new GmailException("Gmail IMAP store cannot be null");
    }
    try {
        name = ((name == null) ? this.srcFolder : name);
        Folder folder = store.getFolder(name);
        if (folder.exists()) {
            return folder;
        }
    } catch (final Exception e) {
        throw new GmailException("ImapGmailClient failed getting " + "Folder: " + name, e);
    }

    throw new GmailException("ImapGmailClient Folder name cannot be null");
}

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;
    Folder folder = null;/*  w w  w.java 2  s .c om*/

    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:de.saly.elasticsearch.mailsource.ParallelPollingIMAPMailSource.java

protected void fetch(final Pattern pattern, final String folderName) throws MessagingException, IOException {

    logger.debug("fetch() - pattern: {}, folderName: {}", pattern, folderName);

    final Store store = Session.getInstance(props).getStore();
    store.connect(user, password);// w w w .  j a v  a 2  s .  c  om

    try {
        for (final String fol : mailDestination.getFolderNames()) {
            if (store.getFolder(fol).exists()) {
                logger.debug("{} exists", fol);
            } else {
                logger.info(
                        "Folder {} does not exist on the server, will remove it (and its content) also locally",
                        fol);
                final RiverState riverState = stateManager.getRiverState(store.getFolder(fol));
                riverState.setExists(false);
                stateManager.setRiverState(riverState);

                try {
                    mailDestination.clearDataForFolder(fol);
                } catch (final Exception e) {
                    stateManager.onError("Unable to clean data for stale folder", store.getFolder(fol), e);
                }
            }
        }
    } catch (final IndexMissingException ime) {
        logger.debug(ime.toString());

    } catch (final Exception e) {
        logger.error("Error checking for stale folders", e);
    }

    final boolean isRoot = StringUtils.isEmpty(folderName);
    final Folder folder = isRoot ? store.getDefaultFolder() : store.getFolder(folderName);

    try {

        if (!folder.exists()) {
            logger.error("Folder {} does not exist on the server", folder.getFullName());
            return;
        }

        logger.debug("folderName: {} is root: {}", folderName, isRoot);

        /*if (logger.isDebugEnabled() && store instanceof IMAPStore) {
                
           IMAPStore imapStore = (IMAPStore) store;
           logger.debug("IMAP server capability info");
           logger.debug("IMAP4rev1: "
             + imapStore.hasCapability("IMAP4rev1"));
           logger.debug("IDLE: " + imapStore.hasCapability("IDLE"));
           logger.debug("ID: " + imapStore.hasCapability("ID"));
           logger.debug("UIDPLUS: " + imapStore.hasCapability("UIDPLUS"));
           logger.debug("CHILDREN: " + imapStore.hasCapability("CHILDREN"));
           logger.debug("NAMESPACE: "
             + imapStore.hasCapability("NAMESPACE"));
           logger.debug("NOTIFY: " + imapStore.hasCapability("NOTIFY"));
           logger.debug("CONDSTORE: "
             + imapStore.hasCapability("CONDSTORE"));
           logger.debug("QRESYNC: " + imapStore.hasCapability("QRESYNC"));
           logger.debug("STATUS: " + imapStore.hasCapability("STATUS"));
        }*/

        if (pattern != null && !isRoot && !pattern.matcher(folder.getFullName()).matches()) {
            logger.info(folder.getFullName() + " does not match pattern " + pattern.toString());
            return;
        }

        IMAPUtils.open(folder);

        recurseFolders(folder, pattern);

    } finally {

        IMAPUtils.close(folder);
        IMAPUtils.close(store);

    }
}

From source file:com.aquest.emailmarketing.web.service.BouncedEmailService.java

/**
 * Process bounces.//from w w  w.  j av a  2  s.  co m
 *
 * @param protocol the protocol
 * @param host the host
 * @param port the port
 * @param userName the user name
 * @param password the password
 */
public void processBounces(String protocol, String host, String port, String userName, String password) {
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);

    List<BounceCode> bounceCodes = bounceCodeService.getAllBounceCodes();

    try {
        // connects to the message store
        Store store = session.getStore(protocol);
        System.out.println(userName);
        System.out.println(password);
        System.out.println(userName.length());
        System.out.println(password.length());
        //store.connect(userName, password);
        //TODO: ispraviti username i password da idu iz poziva a ne hardcoded
        store.connect("bojan.dimic@aquest-solutions.com", "bg181076");

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

        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();

        for (int i = 0; i < messages.length; i++) {
            BouncedEmail bouncedEmail = new BouncedEmail();
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String from = fromAddress[0].toString();
            String failedAddress = "";
            Enumeration<?> headers = messages[i].getAllHeaders();
            while (headers.hasMoreElements()) {
                Header h = (Header) headers.nextElement();
                //System.out.println(h.getName() + ":" + h.getValue());
                //System.out.println("");                
                String mID = h.getName();
                if (mID.contains("X-Failed-Recipients")) {
                    failedAddress = h.getValue();
                }
            }
            String subject = msg.getSubject();
            String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
            String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
            String sentDate = msg.getSentDate().toString();

            String contentType = msg.getContentType();
            String messageContent = "";

            if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                try {
                    Object content = msg.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                } catch (Exception ex) {
                    messageContent = "[Error downloading content]";
                    ex.printStackTrace();
                }
            }

            String bounceReason = "Unknown reason";

            for (BounceCode bounceCode : bounceCodes) {
                if (messageContent.contains(bounceCode.getCode())) {
                    bounceReason = bounceCode.getExplanation();
                }
            }

            //                if(messageContent.contains(" 550 ") || messageContent.contains(" 550-")) {bounceReason="Users mailbox was unavailable (such as not found)";}
            //                if(messageContent.contains(" 554 ") || messageContent.contains(" 554-")) {bounceReason="The transaction failed for some unstated reason.";}
            //                
            //                // enhanced bounce codes
            //                if(messageContent.contains("5.0.0")) {bounceReason="Unknown issue";}
            //                if(messageContent.contains("5.1.0")) {bounceReason="Other address status";}
            //                if(messageContent.contains("5.1.1")) {bounceReason="Bad destination mailbox address";}
            //                if(messageContent.contains("5.1.2")) {bounceReason="Bad destination system address";}
            //                if(messageContent.contains("5.1.3")) {bounceReason="Bad destination mailbox address syntax";}
            //                if(messageContent.contains("5.1.4")) {bounceReason="Destination mailbox address ambiguous";}
            //                if(messageContent.contains("5.1.5")) {bounceReason="Destination mailbox address valid";}
            //                if(messageContent.contains("5.1.6")) {bounceReason="Mailbox has moved";}
            //                if(messageContent.contains("5.7.1")) {bounceReason="Delivery not authorized, message refused";}

            // print out details of each message
            System.out.println("Message #" + (i + 1) + ":");
            System.out.println("\t From: " + from);
            System.out.println("\t To: " + toList);
            System.out.println("\t CC: " + ccList);
            System.out.println("\t Subject: " + subject);
            System.out.println("\t Sent Date: " + sentDate);
            System.out.println("\t X-Failed-Recipients:" + failedAddress);
            System.out.println("\t Content Type:" + contentType);
            System.out.println("\t Bounce reason:" + bounceReason);
            //System.out.println("\t Message: " + messageContent);

            bouncedEmail.setEmail_address(failedAddress);
            bouncedEmail.setBounce_reason(bounceReason);

            //Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
            SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
            //String strDate = date.toString();
            System.out.println(sentDate);
            Date dt = null;
            //Date nd = null;
            try {
                dt = formatter.parse(sentDate);
                //nd = sqlFormat.parse(dt.toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println("Date " + dt.toString());
            //System.out.println("Date " + nd.toString());
            System.out.println(new Timestamp(new Date().getTime()));
            bouncedEmail.setSend_date(dt);
            bouncedEmailDao.saveOrUpdate(bouncedEmail);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        System.out.println("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        System.out.println("Could not connect to the message store");
        ex.printStackTrace();
    }
}

From source file:de.saly.elasticsearch.importer.imap.mailsource.ParallelPollingIMAPMailSource.java

protected void fetch(final Pattern pattern, final String folderName) throws MessagingException, IOException {
    logger.debug("fetch() - pattern: {}, folderName: {}, user: {}", pattern, folderName, user);

    final Store store = Session.getInstance(props).getStore();
    store.connect(user, password);/* w w w . j a v  a  2  s. c o  m*/

    if (deleteExpungedMessages) {

        try {
            for (final String fol : mailDestination.getFolderNames()) {
                if (store.getFolder(fol).exists()) {
                    logger.debug("{} exists for {}", fol, user);
                } else {
                    logger.info(
                            "Folder {} does not exist for {} on the server, will remove it (and its content) also locally",
                            user, fol);
                    final State riverState = stateManager.getRiverState(store.getFolder(fol));
                    riverState.setExists(false);
                    stateManager.setRiverState(riverState);

                    try {
                        mailDestination.clearDataForFolder(store.getFolder(fol));
                    } catch (final Exception e) {
                        stateManager.onError("Unable to clean data for stale folder for " + user,
                                store.getFolder(fol), e);
                    }
                }
            }
        } /*catch (final IndexMissingException ime) {
          logger.debug(ime.toString());
          //TODO 2.0 check
          } */ catch (final Exception e) {
            logger.error("Error checking for stale folders", e);
        }

    }

    final boolean isRoot = StringUtils.isEmpty(folderName);
    final Folder folder = isRoot ? store.getDefaultFolder() : store.getFolder(folderName);

    try {

        if (!folder.exists()) {
            logger.error("Folder {} does not exist on the server", folder.getFullName());
            return;
        }

        logger.debug("folderName: {} is root: {}", folderName, isRoot);

        /*if (logger.isDebugEnabled() && store instanceof IMAPStore) {
                
           IMAPStore imapStore = (IMAPStore) store;
           logger.debug("IMAP server capability info");
           logger.debug("IMAP4rev1: "
             + imapStore.hasCapability("IMAP4rev1"));
           logger.debug("IDLE: " + imapStore.hasCapability("IDLE"));
           logger.debug("ID: " + imapStore.hasCapability("ID"));
           logger.debug("UIDPLUS: " + imapStore.hasCapability("UIDPLUS"));
           logger.debug("CHILDREN: " + imapStore.hasCapability("CHILDREN"));
           logger.debug("NAMESPACE: "
             + imapStore.hasCapability("NAMESPACE"));
           logger.debug("NOTIFY: " + imapStore.hasCapability("NOTIFY"));
           logger.debug("CONDSTORE: "
             + imapStore.hasCapability("CONDSTORE"));
           logger.debug("QRESYNC: " + imapStore.hasCapability("QRESYNC"));
           logger.debug("STATUS: " + imapStore.hasCapability("STATUS"));
        }*/

        if (pattern != null && !isRoot && !pattern.matcher(folder.getFullName()).matches()) {
            logger.debug(folder.getFullName() + " does not match pattern " + pattern.toString());
            return;
        }

        IMAPUtils.open(folder);

        recurseFolders(folder, pattern);

    } finally {

        IMAPUtils.close(folder);
        IMAPUtils.close(store);

    }
}

From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java

/**
 * {@inheritDoc}//from  w  w w.  j  a v  a2s .c o m
 */
@Override
public SampleResult sample(Entry e) {
    SampleResult parent = new SampleResult();
    boolean isOK = false; // Did sample succeed?
    final boolean deleteMessages = getDeleteMessages();
    final String serverProtocol = getServerType();

    parent.setSampleLabel(getName());

    String samplerString = toString();
    parent.setSamplerData(samplerString);

    /*
     * Perform the sampling
     */
    parent.sampleStart(); // Start timing
    try {
        // Create empty properties
        Properties props = new Properties();

        if (isUseStartTLS()) {
            props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE); // $NON-NLS-1$
            if (isEnforceStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE); // $NON-NLS-1$
            }
        }

        if (isTrustAllCerts()) {
            if (isUseSSL()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        } else if (isUseLocalTrustStore()) {
            File truststore = new File(getTrustStoreToUse());
            log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                log.info("load local truststore -Failed to load truststore from: "
                        + truststore.getAbsolutePath());
                truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse());
                log.info("load local truststore -Attempting to read truststore from:  "
                        + truststore.getAbsolutePath());
                if (!truststore.exists()) {
                    log.info("load local truststore -Failed to load truststore from: "
                            + truststore.getAbsolutePath()
                            + ". Local truststore not available, aborting execution.");
                    throw new IOException("Local truststore file not found. Also not available under : "
                            + truststore.getAbsolutePath());
                }
            }
            if (isUseSSL()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ 
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        }

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

        // Get the store
        Store store = session.getStore(serverProtocol);
        store.connect(getServer(), getPortAsInt(), getUserName(), getPassword());

        // Get folder
        Folder folder = store.getFolder(getFolder());
        if (deleteMessages) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }

        final int messageTotal = folder.getMessageCount();
        int n = getNumMessages();
        if (n == ALL_MESSAGES || n > messageTotal) {
            n = messageTotal;
        }

        // Get directory
        Message[] messages = folder.getMessages(1, n);
        StringBuilder pdata = new StringBuilder();
        pdata.append(messages.length);
        pdata.append(" messages found\n");
        parent.setResponseData(pdata.toString(), null);
        parent.setDataType(SampleResult.TEXT);
        parent.setContentType("text/plain"); // $NON-NLS-1$

        final boolean headerOnly = getHeaderOnly();
        busy = true;
        for (Message message : messages) {
            StringBuilder cdata = new StringBuilder();
            SampleResult child = new SampleResult();
            child.sampleStart();

            cdata.append("Message "); // $NON-NLS-1$
            cdata.append(message.getMessageNumber());
            child.setSampleLabel(cdata.toString());
            child.setSamplerData(cdata.toString());
            cdata.setLength(0);

            final String contentType = message.getContentType();
            child.setContentType(contentType);// Store the content-type
            child.setDataEncoding(RFC_822_DEFAULT_ENCODING); // RFC 822 uses ascii per default
            child.setEncodingAndType(contentType);// Parse the content-type

            if (isStoreMimeMessage()) {
                // Don't save headers - they are already in the raw message
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                message.writeTo(bout);
                child.setResponseData(bout.toByteArray()); // Save raw message
                child.setDataType(SampleResult.TEXT);
            } else {
                @SuppressWarnings("unchecked") // Javadoc for the API says this is OK
                Enumeration<Header> hdrs = message.getAllHeaders();
                while (hdrs.hasMoreElements()) {
                    Header hdr = hdrs.nextElement();
                    String value = hdr.getValue();
                    try {
                        value = MimeUtility.decodeText(value);
                    } catch (UnsupportedEncodingException uce) {
                        // ignored
                    }
                    cdata.append(hdr.getName()).append(": ").append(value).append("\n");
                }
                child.setResponseHeaders(cdata.toString());
                cdata.setLength(0);
                if (!headerOnly) {
                    appendMessageData(child, message);
                }
            }

            if (deleteMessages) {
                message.setFlag(Flags.Flag.DELETED, true);
            }
            child.setResponseOK();
            if (child.getEndTime() == 0) {// Avoid double-call if addSubResult was called.
                child.sampleEnd();
            }
            parent.addSubResult(child);
        }

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

        parent.setResponseCodeOK();
        parent.setResponseMessageOK();
        isOK = true;
    } catch (NoClassDefFoundError | IOException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString());
    } catch (MessagingException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString() + "\n" + samplerString); // $NON-NLS-1$
    } finally {
        busy = false;
    }

    if (parent.getEndTime() == 0) {// not been set by any child samples
        parent.sampleEnd();
    }
    parent.setSuccessful(isOK);
    return parent;
}

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

protected Folder getFolder(String fullName) throws MailException, MessagingException {

    Store store = _imapConnection.getStore(true);

    return store.getFolder(fullName);
}