Example usage for javax.mail NoSuchProviderException printStackTrace

List of usage examples for javax.mail NoSuchProviderException printStackTrace

Introduction

In this page you can find the example usage for javax.mail NoSuchProviderException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:net.prhin.mailman.MailMan.java

public static void main(String[] args) {
    Properties props = new Properties();
    props.setProperty(resourceBundle.getString("mailman.mail.store"),
            resourceBundle.getString("mailman.protocol"));

    Session session = Session.getInstance(props);

    try {//from w w  w . j  a va 2  s. c  o  m

        Store store = session.getStore();
        store.connect(resourceBundle.getString("mailman.host"), resourceBundle.getString("mailman.user"),
                resourceBundle.getString("mailman.password"));
        Folder inbox = store.getFolder(resourceBundle.getString("mailman.folder"));
        inbox.open(Folder.READ_ONLY);
        inbox.getUnreadMessageCount();
        Message[] messages = inbox.getMessages();

        for (int i = 0; i <= messages.length / 2; i++) {
            Message tmpMessage = messages[i];

            Multipart multipart = (Multipart) tmpMessage.getContent();

            System.out.println("Multipart count: " + multipart.getCount());

            for (int j = 0; j < multipart.getCount(); j++) {
                BodyPart bodyPart = multipart.getBodyPart(j);

                if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
                    if (bodyPart.getContent().getClass().equals(MimeMultipart.class)) {
                        MimeMultipart mimeMultipart = (MimeMultipart) bodyPart.getContent();

                        for (int k = 0; k < mimeMultipart.getCount(); k++) {
                            if (mimeMultipart.getBodyPart(k).getFileName() != null) {
                                printFileContents(mimeMultipart.getBodyPart(k));
                            }
                        }
                    }
                } else {
                    printFileContents(bodyPart);
                }
            }
        }

        inbox.close(false);
        store.close();

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

}

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

/**
 * @param args/*  ww w  .  jav a  2s. c o m*/
 */
public static void main(String[] args) {
    // get a connection to the mail server
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", protocol);
    props.setProperty("mail.imaps.partialfetch", prefetch);

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

    try {

        // create the imaps mail session
        mailSession = Session.getDefaultInstance(props, null);
        mailStore = mailSession.getStore(protocol);
        mailStore.connect(server, username, password);
        // get folder references for the inbox and processed data box

        //createFolders(targetMailbox);

        organizeMessages(sourceMailbox, targetMailbox);

    } catch (NoSuchProviderException nspe) {
        nspe.printStackTrace();

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

    } finally {
        try {
            mailStore.close();

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

        }
    }
}

From source file:registry.java

public static void main(String[] args) {
    Properties props = new Properties();

    // set smtp and imap to be our default 
    // transport and store protocols, respectively
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.store.protocol", "imap");

    // //  ww w  .ja v a2  s.c o m
    props.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
    props.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");

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

    // Retrieve all configured providers from the Session
    System.out.println("\n------ getProviders()----------");
    Provider[] providers = session.getProviders();
    for (int i = 0; i < providers.length; i++) {
        System.out.println("** " + providers[i]);

        // let's remember some providers so that we can use them later
        // (I'm explicitly showing multiple ways of testing Providers)
        // BTW, no Provider "ACME Corp" will be found in the default
        // setup b/c its not in any javamail.providers resource files
        String s = null;
        if (((s = providers[i].getVendor()) != null) && s.startsWith("ACME Corp")) {
            _aProvider = providers[i];
        }

        // this Provider won't be found by default either
        if (providers[i].getClassName().endsWith("application.smtp"))
            _bProvider = providers[i];

        // this Provider will be found since com.sun.mail.imap.IMAPStore
        // is configured in javamail.default.providers
        if (providers[i].getClassName().equals("com.sun.mail.imap.IMAPStore")) {
            _sunIMAP = providers[i];
        }

        // this Provider will be found as well since there is an
        // Oracle SMTP transport configured by 
        // default in javamail.default.providers
        if (((s = providers[i].getVendor()) != null) && s.startsWith("Oracle")
                && providers[i].getType() == Provider.Type.TRANSPORT
                && providers[i].getProtocol().equalsIgnoreCase("smtp")) {
            _sunSMTP = providers[i];
        }
    }

    System.out.println("\n------ initial protocol defaults -------");
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
        // the NNTP provider will fail since we don't have one configured
        System.out.println("nntp: " + session.getProvider("nntp"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> This exception is OK since there is no NNTP Provider configured by default");
        mex.printStackTrace();
    }

    System.out.println("\n------ set new protocol defaults ------");
    // set some new defaults
    try {
        // since _aProvider isn't configured, this will fail
        session.setProvider(_aProvider); // will fail
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: _aProvider is null");
        mex.printStackTrace();
    }
    try {
        // _sunIMAP provider should've configured correctly; should work
        session.setProvider(_sunIMAP);
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    System.out.println("\n\n----- get some stores ---------");
    // multiple ways to retrieve stores. these will print out the
    // string "imap:" since its the URLName for the store
    try {
        System.out.println("getStore(): " + session.getStore());
        System.out.println("getStore(Provider): " + session.getStore(_sunIMAP));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    try {
        System.out.println("getStore(imap): " + session.getStore("imap"));
        // pop3 will fail since it doesn't exist
        System.out.println("getStore(pop3): " + session.getStore("pop3"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: no pop3 provider");
        mex.printStackTrace();
    }

    System.out.println("\n\n----- now for transports/addresses ---------");
    // retrieve transports; these will print out "smtp:" (like stores did)
    try {
        System.out.println("getTransport(): " + session.getTransport());
        System.out.println("getTransport(Provider): " + session.getTransport(_sunSMTP));
        System.out.println("getTransport(smtp): " + session.getTransport("smtp"));
        System.out.println(
                "getTransport(Address): " + session.getTransport(new InternetAddress("mspivak@apilon")));
        // News will fail since there's no news provider configured
        System.out.println("getTransport(News): " + session.getTransport(new NewsAddress("rec.humor")));
    } catch (MessagingException mex) {
        System.out.println(">> Exception expected: no news provider configured");
        mex.printStackTrace();
    }
}

From source file:registry.java

public static void main(String[] args) {
    Properties props = new Properties();

    // set smtp and imap to be our default
    // transport and store protocols, respectively
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.store.protocol", "imap");

    // //from  w ww. j  a  v  a  2 s. c  o m
    props.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
    props.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");

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

    // Retrieve all configured providers from the Session
    System.out.println("\n------ getProviders()----------");
    Provider[] providers = session.getProviders();
    for (int i = 0; i < providers.length; i++) {
        System.out.println("** " + providers[i]);

        // let's remember some providers so that we can use them later
        // (I'm explicitly showing multiple ways of testing Providers)
        // BTW, no Provider "ACME Corp" will be found in the default
        // setup b/c its not in any javamail.providers resource files
        String s = null;
        if (((s = providers[i].getVendor()) != null) && s.startsWith("ACME Corp")) {
            _aProvider = providers[i];
        }

        // this Provider won't be found by default either
        if (providers[i].getClassName().endsWith("application.smtp"))
            _bProvider = providers[i];

        // this Provider will be found since com.sun.mail.imap.IMAPStore
        // is configured in javamail.default.providers
        if (providers[i].getClassName().equals("com.sun.mail.imap.IMAPStore")) {
            _sunIMAP = providers[i];
        }

        // this Provider will be found as well since there is a
        // Sun Microsystems SMTP transport configured by
        // default in javamail.default.providers
        if (((s = providers[i].getVendor()) != null) && s.startsWith("Sun Microsystems")
                && providers[i].getType() == Provider.Type.TRANSPORT
                && providers[i].getProtocol().equalsIgnoreCase("smtp")) {
            _sunSMTP = providers[i];
        }
    }

    System.out.println("\n------ initial protocol defaults -------");
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
        // the NNTP provider will fail since we don't have one configured
        System.out.println("nntp: " + session.getProvider("nntp"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> This exception is OK since there is no NNTP Provider configured by default");
        mex.printStackTrace();
    }

    System.out.println("\n------ set new protocol defaults ------");
    // set some new defaults
    try {
        // since _aProvider isn't configured, this will fail
        session.setProvider(_aProvider); // will fail
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: _aProvider is null");
        mex.printStackTrace();
    }
    try {
        // _sunIMAP provider should've configured correctly; should work
        session.setProvider(_sunIMAP);
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    System.out.println("\n\n----- get some stores ---------");
    // multiple ways to retrieve stores. these will print out the
    // string "imap:" since its the URLName for the store
    try {
        System.out.println("getStore(): " + session.getStore());
        System.out.println("getStore(Provider): " + session.getStore(_sunIMAP));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    try {
        System.out.println("getStore(imap): " + session.getStore("imap"));
        // pop3 will fail since it doesn't exist
        System.out.println("getStore(pop3): " + session.getStore("pop3"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: no pop3 provider");
        mex.printStackTrace();
    }

    System.out.println("\n\n----- now for transports/addresses ---------");
    // retrieve transports; these will print out "smtp:" (like stores did)
    try {
        System.out.println("getTransport(): " + session.getTransport());
        System.out.println("getTransport(Provider): " + session.getTransport(_sunSMTP));
        System.out.println("getTransport(smtp): " + session.getTransport("smtp"));
        System.out.println(
                "getTransport(Address): " + session.getTransport(new InternetAddress("mspivak@apilon")));
        // News will fail since there's no news provider configured
        System.out.println("getTransport(News): " + session.getTransport(new NewsAddress("rec.humor")));
    } catch (MessagingException mex) {
        System.out.println(">> Exception expected: no news provider configured");
        mex.printStackTrace();
    }
}

From source file:eu.forgestore.ws.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody) {

    Properties props = new Properties();

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

    props.setProperty("mail.transport.protocol", "smtp");
    if ((FStoreRepository.getPropertyByName("mailhost").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", FStoreRepository.getPropertyByName("mailhost").getValue());
    if ((FStoreRepository.getPropertyByName("mailuser").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", FStoreRepository.getPropertyByName("mailuser").getValue());
    if ((FStoreRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", FStoreRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = FStoreRepository.getPropertyByName("adminEmail").getValue();
    String subj = FStoreRepository.getPropertyByName("activationEmailSubject").getValue();
    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport;/*  w  w  w .  j  av  a  2  s  . c  o m*/
    try {
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:gr.upatras.ece.nam.baker.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody) {

    Properties props = new Properties();

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

    props.setProperty("mail.transport.protocol", "smtp");
    if ((BakerRepository.getPropertyByName("mailhost").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", BakerRepository.getPropertyByName("mailhost").getValue());
    if ((BakerRepository.getPropertyByName("mailuser").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", BakerRepository.getPropertyByName("mailuser").getValue());
    if ((BakerRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", BakerRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = BakerRepository.getPropertyByName("adminEmail").getValue();
    String subj = BakerRepository.getPropertyByName("activationEmailSubject").getValue();
    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport;/*from   w w  w .j a  v a2  s. c o m*/
    try {
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:pt.lsts.neptus.comm.iridium.RockBlockIridiumMessenger.java

@Override
public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception {

    if (askGmailPassword || gmailPassword == null || gmailUsername == null) {
        Pair<String, String> credentials = GuiUtils.askCredentials(ConfigFetch.getSuperParentFrame(),
                "Enter Gmail Credentials", getGmailUsername(), getGmailPassword());
        if (credentials == null)
            return null;
        setGmailUsername(credentials.first());
        setGmailPassword(credentials.second());
        PluginUtils.saveProperties("conf/rockblock.props", this);
        askGmailPassword = false;/*from w  w w  .ja  v  a 2  s . c o  m*/
    }

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

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

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

    return messages;
}

From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java

/**
 * Returns new messages and fetches details for each message.
 *//*from w  w w  .  j a  v a 2 s  .  c  o  m*/
@Transactional(readOnly = false)
public ResultClass<Boolean> downloadEmails() {

    ResultClass<Boolean> result = new ResultClass<>();
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);

    try {

        // connects to the message store
        Store store = session.getStore(protocol);

        store.connect(userName, password);
        // 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++) {
            Message msg = messages[i];

            String[] idHeaders = msg.getHeader("MESSAGE-ID");
            if (idHeaders != null && idHeaders.length > 0) {

                MessageBox exists = repositoryMailBox.getMessageBox(idHeaders[0]);
                if (exists == null) {

                    MessageBox messageBox = new MessageBox();
                    messageBox.setSubject(msg.getSubject());
                    messageBox.setCode(idHeaders[0]);

                    Address[] fromAddresses = msg.getFrom();
                    String from = InternetAddress.toString(fromAddresses);

                    if (from.startsWith("=?")) {
                        from = MimeUtility.decodeWord(from);
                    }
                    messageBox.setFrom(from);
                    String to = InternetAddress.toString(msg.getRecipients(RecipientType.TO));

                    if (to.startsWith("=?")) {
                        to = MimeUtility.decodeWord(to);
                    }
                    messageBox.setTo(to);

                    String[] replyHeaders = msg.getHeader("References");

                    if (replyHeaders != null && replyHeaders.length > 0) {
                        StringTokenizer tokens = new StringTokenizer(replyHeaders[0]);
                        MessageBox parent = repositoryMailBox.getMessageBox(tokens.nextToken());
                        if (parent != null)
                            parent.addReply(messageBox);
                    }

                    result = parseSubjectAndCreate(messageBox, msg);
                }
            }
        }

        folderInbox.close(false);
        store.close();

        return result;

    } catch (NoSuchProviderException ex) {
        logger.error("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store");
        ex.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }
    result.setSingleElement(false);
    return result;
}

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.
 *//*w w w . j  a  va 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:org.alfresco.repo.imap.RemoteLoadTester.java

public void testListSequence() {
    System.out.println(String.format("Connecting to remote server '%s'", REMOTE_HOST));
    Properties props = System.getProperties();
    props.setProperty("mail.imap.partialfetch", "false");
    Session session = Session.getDefaultInstance(props, null);

    Store store = null;/*from w  w  w  .  j  ava 2s  . c  om*/
    long startTime = 0;
    long endTime = 0;
    try {
        store = session.getStore("imap");
        store.connect(REMOTE_HOST, ADMIN_USER_NAME, ADMIN_USER_NAME);
        Folder[] folders = null;

        startTime = System.currentTimeMillis();
        folders = store.getDefaultFolder().list("");
        endTime = System.currentTimeMillis();
        System.out.println(String.format("LIST '', folders.length = %d, execTime = %d sec", folders.length,
                (endTime - startTime) / 1000));

        startTime = System.currentTimeMillis();
        folders = store.getDefaultFolder().list("*");
        endTime = System.currentTimeMillis();
        System.out.println(String.format("LIST *, folders.length = %d, execTime = %d sec", folders.length,
                (endTime - startTime) / 1000));

        startTime = System.currentTimeMillis();
        folders = store.getDefaultFolder().listSubscribed("*");
        endTime = System.currentTimeMillis();
        System.out.println(String.format("LSUB *, folders.length = %d, execTime = %d sec", folders.length,
                (endTime - startTime) / 1000));

        startTime = System.currentTimeMillis();
        for (Folder folder : folders) {
            folder.getMessageCount();
            //Folder f = store.getFolder(folder.getFullName());
        }
        endTime = System.currentTimeMillis();
        System.out.println(String.format("Folders Loop, folders.length = %d, execTime = %d sec", folders.length,
                (endTime - startTime) / 1000));

    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    } finally {
        try {
            store.close();
        } catch (MessagingException e) {
            System.err.println(e.getMessage());
        }
    }
}