Example usage for javax.mail NoSuchProviderException getMessage

List of usage examples for javax.mail NoSuchProviderException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.ikon.util.MailUtils.java

/**
 * Test IMAP connection//from w  w  w.  j  a v a  2 s.c o m
 */
public static void testConnection(MailAccount ma) throws IOException {
    log.debug("testConnection({})", ma);
    Session session = Session.getDefaultInstance(getProperties());
    Store store = null;
    Folder folder = null;

    try {
        store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());
        folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        folder.close(false);
    } catch (NoSuchProviderException e) {
        throw new IOException(e.getMessage());
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    } finally {
        // Try to close folder
        if (folder != null && folder.isOpen()) {
            try {
                folder.close(false);
            } catch (MessagingException e) {
                throw new IOException(e.getMessage());
            }
        }

        // Try to close store
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                throw new IOException(e.getMessage());
            }
        }
    }

    log.debug("testConnection: void");
}

From source file:com.ikon.util.MailUtils.java

/**
 * Import messages/* w w  w  .  j  av  a  2  s.  c  o  m*/
 * http://www.jguru.com/faq/view.jsp?EID=26898
 * 
 * == Using Unique Identifier (UIDL) ==
 * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL
 * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is
 * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email,
 * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't
 * receive it; otherwise receive it.
 * 
 * == Different property of UIDL in POP3 and IMAP4 ==
 * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid
 * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted
 * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is
 * no longer exist on the POP3 server.
 * 
 * == Remarks ==
 * You should create different local uidl list for different email account, because the uidl is only
 * unique for the same account.
 */
public static String importMessages(String token, MailAccount ma) throws PathNotFoundException,
        ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException,
        DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException {
    log.debug("importMessages({}, {})", new Object[] { token, ma });
    Session session = Session.getDefaultInstance(getProperties());
    String exceptionMessage = null;

    try {
        // Open connection
        Store store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());

        Folder folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        Message messages[] = null;

        if (folder instanceof IMAPFolder) {
            // IMAP folder UIDs begins at 1 and are supposed to be sequential.
            // Each folder has its own UIDs sequence, not is a global one.
            messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID);
        } else {
            messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            log.info(i + ": " + msg.getFrom()[0] + " " + msg.getSubject() + " " + msg.getContentType());
            log.info("Received: " + msg.getReceivedDate());
            log.info("Sent: " + msg.getSentDate());
            log.debug("{} -> {} - {}", new Object[] { i, msg.getSubject(), msg.getReceivedDate() });
            com.ikon.bean.Mail mail = messageToMail(msg);

            if (ma.getMailFilters().isEmpty()) {
                log.debug("Import in compatibility mode");
                String mailPath = getUserMailPath(ma.getUser());
                importMail(token, mailPath, true, folder, msg, ma, mail);
            } else {
                for (MailFilter mf : ma.getMailFilters()) {
                    log.debug("MailFilter: {}", mf);

                    if (checkRules(mail, mf.getFilterRules())) {
                        String mailPath = mf.getPath();
                        importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail);
                    }
                }
            }

            // Set message as seen
            if (ma.isMailMarkSeen()) {
                msg.setFlag(Flags.Flag.SEEN, true);
            } else {
                msg.setFlag(Flags.Flag.SEEN, false);
            }

            // Delete read mail if requested
            if (ma.isMailMarkDeleted()) {
                msg.setFlag(Flags.Flag.DELETED, true);
            }

            // Set lastUid
            if (folder instanceof IMAPFolder) {
                long msgUid = ((IMAPFolder) folder).getUID(msg);
                log.info("Message UID: {}", msgUid);
                ma.setMailLastUid(msgUid);
                MailAccountDAO.update(ma);
            }
        }

        // Close connection
        log.debug("Expunge: {}", ma.isMailMarkDeleted());
        folder.close(ma.isMailMarkDeleted());
        store.close();
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    }

    log.debug("importMessages: {}", exceptionMessage);
    return exceptionMessage;
}

From source file:com.openkm.util.MailUtils.java

/**
 * Import messages//from w w w.ja  v a 2s. c  o  m
 * http://www.jguru.com/faq/view.jsp?EID=26898
 * 
 * == Using Unique Identifier (UIDL) ==
 * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL
 * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is
 * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email,
 * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't
 * receive it; otherwise receive it.
 * 
 * == Different property of UIDL in POP3 and IMAP4 ==
 * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid
 * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted
 * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is
 * no longer exist on the POP3 server.
 * 
 * == Remarks ==
 * You should create different local uidl list for different email account, because the uidl is only
 * unique for the same account.
 */
public static String importMessages(String token, MailAccount ma) throws PathNotFoundException,
        ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException,
        DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException {
    log.debug("importMessages({}, {})", new Object[] { token, ma });
    Session session = Session.getDefaultInstance(getProperties());
    String exceptionMessage = null;

    try {
        // Open connection
        Store store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());

        Folder folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        Message messages[] = null;

        if (folder instanceof IMAPFolder) {
            // IMAP folder UIDs begins at 1 and are supposed to be sequential.
            // Each folder has its own UIDs sequence, not is a global one.
            messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID);
        } else {
            messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            log.info("======= ======= {} ======= =======", i);
            log.info("Subject: {}", msg.getSubject());
            log.info("From: {}", msg.getFrom());
            log.info("Received: {}", msg.getReceivedDate());
            log.info("Sent: {}", msg.getSentDate());
            com.openkm.bean.Mail mail = messageToMail(msg);

            if (ma.getMailFilters().isEmpty()) {
                log.debug("Import in compatibility mode");
                String mailPath = getUserMailPath(ma.getUser());
                importMail(token, mailPath, true, folder, msg, ma, mail);
            } else {
                for (MailFilter mf : ma.getMailFilters()) {
                    log.debug("MailFilter: {}", mf);

                    if (checkRules(mail, mf.getFilterRules())) {
                        String mailPath = mf.getPath();
                        importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail);
                    }
                }
            }

            // Set message as seen
            if (ma.isMailMarkSeen()) {
                msg.setFlag(Flags.Flag.SEEN, true);
            } else {
                msg.setFlag(Flags.Flag.SEEN, false);
            }

            // Delete read mail if requested
            if (ma.isMailMarkDeleted()) {
                msg.setFlag(Flags.Flag.DELETED, true);
            }

            // Set lastUid
            if (folder instanceof IMAPFolder) {
                long msgUid = ((IMAPFolder) folder).getUID(msg);
                log.info("Message UID: {}", msgUid);
                ma.setMailLastUid(msgUid);
                MailAccountDAO.update(ma);
            }
        }

        // Close connection
        log.debug("Expunge: {}", ma.isMailMarkDeleted());
        folder.close(ma.isMailMarkDeleted());
        store.close();
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    }

    log.debug("importMessages: {}", exceptionMessage);
    return exceptionMessage;
}

From source file:be.ibridge.kettle.job.entry.getpop.JobEntryGetPOP.java

public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = new Result(nr);
    result.setResult(false);//from   w  w w .  ja  va2s .c  o  m
    result.setNrErrors(1);

    FileObject fileObject = null;

    //Get system properties

    //Properties prop = System.getProperties();
    Properties prop = new Properties();

    //Create session object
    //Session sess = Session.getDefaultInstance(prop,null);
    Session sess = Session.getInstance(prop, null);
    sess.setDebug(true);

    try {

        int nbrmailtoretrieve = Const.toInt(firstmails, 0);
        fileObject = KettleVFS.getFileObject(getRealOutputDirectory());

        // Check if output folder exists
        if (!fileObject.exists()) {
            log.logError(toString(),
                    Messages.getString("JobGetMailsFromPOP.FolderNotExists1.Label") + getRealOutputDirectory()
                            + Messages.getString("JobGetMailsFromPOP.FolderNotExists2.Label"));
        } else {

            String host = getRealServername();
            String user = getRealUsername();
            String pwd = getRealPassword();

            Store st = null;

            if (!getUseSSL()) {

                //Create POP3 object               
                st = sess.getStore("pop3");

                // Try to connect to the server
                st.connect(host, user, pwd);
            } else {
                // Ssupports POP3 connection with SSL, the connection is established via SSL.

                String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

                //Properties pop3Props = new Properties();

                prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
                prop.setProperty("mail.pop3.socketFactory.fallback", "false");
                prop.setProperty("mail.pop3.port", getRealSSLPort());
                prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort());

                URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd);

                st = new POP3SSLStore(sess, url);

                st.connect();

            }

            log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user);

            //Open default folder   INBOX 
            Folder f = st.getFolder("INBOX");
            f.open(Folder.READ_ONLY);

            if (f == null) {
                log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label"));

            } else {

                log.logDetailed(toString(),
                        Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder1.Label") + f.getName()
                                + Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder2.Label")
                                + f.getMessageCount());
                log.logDetailed(toString(),
                        Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder1.Label") + f.getName()
                                + Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder2.Label")
                                + f.getNewMessageCount());

                // Get emails 
                Message msg_list[] = getPOPMessages(f, retrievemails);

                if (msg_list.length > 0) {
                    List current_file_POP = new ArrayList();
                    List current_filepath_POP = new ArrayList();
                    int nb_email_POP = 1;
                    DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy");

                    String startpattern = "name";
                    if (!Const.isEmpty(getRealFilenamePattern())) {
                        startpattern = getRealFilenamePattern();
                    }

                    for (int i = 0; i < msg_list.length; i++)

                    {

                        /*if(msg[i].isMimeType("text/plain"))
                         {
                         log.logDetailed(toString(), "Expediteur: "+msg[i].getFrom()[0]);
                         log.logDetailed(toString(), "Sujet: "+msg[i].getSubject());
                         log.logDetailed(toString(), "Texte: "+(String)msg[i].getContent());
                                
                         }*/

                        if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) {

                            Message msg_POP = msg_list[i];
                            log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label")
                                    + msg_list[i].getFrom()[0]);
                            log.logDetailed(toString(),
                                    Messages.getString("JobGetMailsFromPOP.EmailSubject.Label")
                                            + msg_list[i].getSubject());

                            String localfilename_message = startpattern + "_" + dateFormat.format(new Date())
                                    + "_" + (i + 1) + ".mail";

                            log.logDetailed(toString(),
                                    Messages.getString("JobGetMailsFromPOP.LocalFilename1.Label")
                                            + localfilename_message
                                            + Messages.getString("JobGetMailsFromPOP.LocalFilename2.Label"));

                            File filename_message = new File(getRealOutputDirectory(), localfilename_message);
                            OutputStream os_filename = new FileOutputStream(filename_message);
                            Enumeration enums_POP = msg_POP.getAllHeaders();
                            while (enums_POP.hasMoreElements())

                            {
                                Header header_POP = (Header) enums_POP.nextElement();
                                os_filename.write(new StringBuffer(header_POP.getName()).append(": ")
                                        .append(header_POP.getValue()).append("\r\n").toString().getBytes());
                            }
                            os_filename.write("\r\n".getBytes());
                            InputStream in_POP = msg_POP.getInputStream();
                            byte[] buffer_POP = new byte[1024];
                            int length_POP = 0;
                            while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) {
                                os_filename.write(buffer_POP, 0, length_POP);
                            }
                            os_filename.close();
                            nb_email_POP++;
                            current_file_POP.add(filename_message);
                            current_filepath_POP.add(filename_message.getPath());

                            if (delete) {
                                log.logDetailed(toString(),
                                        Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label"));
                                msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true);
                            }
                        }

                    }
                }
                // Close and exit 
                if (f != null)
                    f.close(false);
                if (st != null)
                    st.close();

                f = null;
                st = null;
                sess = null;

                result.setNrErrors(0);
                result.setResult(true);

            }
        }

    }

    catch (NoSuchProviderException e) {
        log.logError(toString(), "provider error: " + e.getMessage());
    } catch (MessagingException e) {
        log.logError(toString(), "Message error: " + e.getMessage());
    }

    catch (Exception e) {
        log.logError(toString(), "Inexpected error: " + e.getMessage());
    }

    finally {
        if (fileObject != null) {
            try {
                fileObject.close();
            } catch (IOException ex) {
            }
            ;
        }
        sess = null;

    }

    return result;
}

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

/**
 * /* ww w.j  av a  2  s.  co  m*/
 */
private IMAPStore createStore() {

    IMAPStore store = null;
    try {
        store = (IMAPStore) session.getStore();
    } catch (NoSuchProviderException e) {
        logger.error(e.getMessage(), e);
    }

    return store;
}

From source file:com.cubusmail.server.mail.imap.IMAPMailbox.java

/**
 * /*from w ww  .  j ava  2  s .c  om*/
 */
private IMAPStore createStore() {

    IMAPStore store = null;
    try {
        store = (IMAPStore) session.getStore();
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
    }

    return store;
}

From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java

@SuppressWarnings({ "unchecked" })
public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);/* ww  w  .  j  a v a 2  s . c o m*/
    result.setNrErrors(1);

    //Get system properties
    Properties prop = new Properties();
    prop.setProperty("mail.pop3s.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    prop.setProperty("mail.pop3.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    //Create session object
    Session sess = Session.getDefaultInstance(prop, null);
    sess.setDebug(true);

    FileObject fileObject = null;
    Store st = null;
    Folder f = null;
    try {
        int nbrmailtoretrieve = Const.toInt(firstmails, 0);
        String realOutputFolder = getRealOutputDirectory();
        fileObject = KettleVFS.getFileObject(realOutputFolder);

        // Check if output folder exists
        if (!fileObject.exists()) {
            log.logError(toString(),
                    Messages.getString("JobGetMailsFromPOP.FolderNotExists.Label", realOutputFolder)); //$NON-NLS-1$
        } else {
            if (fileObject.getType() == FileType.FOLDER) {
                String host = getRealServername();
                String user = getRealUsername();
                String pwd = getRealPassword();

                if (!getUseSSL()) {
                    //Create POP3 object
                    st = sess.getStore("pop3"); //$NON-NLS-1$

                    // Try to connect to the server
                    st.connect(host, user, pwd);
                } else {
                    // Ssupports POP3 connection with SSL, the connection is established via SSL.

                    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //$NON-NLS-1$
                    prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); //$NON-NLS-1$
                    prop.setProperty("mail.pop3.socketFactory.fallback", "false"); //$NON-NLS-1$ //$NON-NLS-2$
                    prop.setProperty("mail.pop3.port", getRealSSLPort()); //$NON-NLS-1$
                    prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); //$NON-NLS-1$

                    URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); //$NON-NLS-1$ //$NON-NLS-2$
                    st = new POP3SSLStore(sess, url);
                    st.connect();
                }
                if (log.isDetailed())
                    log.logDetailed(toString(),
                            Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //$NON-NLS-1$

                //Open the INBOX FOLDER
                // For POP3, the only folder available is the INBOX.
                f = st.getFolder("INBOX"); //$NON-NLS-1$

                if (f == null) {
                    log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); //$NON-NLS-1$

                } else {
                    // Open folder
                    if (delete)
                        f.open(Folder.READ_WRITE);
                    else
                        f.open(Folder.READ_ONLY);

                    Message messageList[] = f.getMessages();
                    if (log.isDetailed()) {
                        log.logDetailed(toString(),
                                Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder.Label", f.getName(), //$NON-NLS-1$
                                        String.valueOf(messageList.length)));
                        log.logDetailed(toString(),
                                Messages.getString("JobGetMailsFromPOP.TotalUnreadMessagesFolder.Label", //$NON-NLS-1$
                                        f.getName(), String.valueOf(f.getUnreadMessageCount())));
                    }
                    // Get emails
                    Message msg_list[] = getPOPMessages(f, retrievemails);

                    if (msg_list.length > 0) {
                        List<File> current_file_POP = new ArrayList<File>();
                        List<String> current_filepath_POP = new ArrayList<String>();
                        int nb_email_POP = 1;

                        String startpattern = "name"; //$NON-NLS-1$
                        if (!Const.isEmpty(getRealFilenamePattern())) {
                            startpattern = getRealFilenamePattern();
                        }

                        for (int i = 0; i < msg_list.length; i++) {
                            if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2)
                                    || (retrievemails != 2)) {
                                Message msg_POP = msg_list[i];
                                if (log.isDetailed()) {
                                    log.logDetailed(toString(),
                                            Messages.getString("JobGetMailsFromPOP.EmailFrom.Label", //$NON-NLS-1$
                                                    msg_list[i].getFrom()[0].toString()));
                                    log.logDetailed(toString(), Messages.getString(
                                            "JobGetMailsFromPOP.EmailSubject.Label", msg_list[i].getSubject())); //$NON-NLS-1$
                                }
                                String localfilename_message = startpattern + "_" //$NON-NLS-1$
                                        + StringUtil.getFormattedDateTimeNow(true) + "_" + (i + 1) + ".mail"; //$NON-NLS-1$ //$NON-NLS-2$
                                if (log.isDetailed())
                                    log.logDetailed(toString(), Messages.getString(
                                            "JobGetMailsFromPOP.LocalFilename.Label", localfilename_message)); //$NON-NLS-1$

                                File filename_message = new File(realOutputFolder, localfilename_message);
                                OutputStream os_filename = new FileOutputStream(filename_message);
                                Enumeration<Header> enums_POP = msg_POP.getAllHeaders();
                                while (enums_POP.hasMoreElements())

                                {
                                    Header header_POP = enums_POP.nextElement();
                                    os_filename.write(new StringBuffer(header_POP.getName()).append(": ") //$NON-NLS-1$
                                            .append(header_POP.getValue()).append("\r\n").toString().getBytes()); //$NON-NLS-1$
                                }
                                os_filename.write("\r\n".getBytes()); //$NON-NLS-1$
                                InputStream in_POP = msg_POP.getInputStream();
                                byte[] buffer_POP = new byte[1024];
                                int length_POP = 0;
                                while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) {
                                    os_filename.write(buffer_POP, 0, length_POP);

                                }
                                os_filename.close();
                                nb_email_POP++;
                                current_file_POP.add(filename_message);
                                current_filepath_POP.add(filename_message.getPath());

                                // Check attachments
                                Object content = msg_POP.getContent();
                                if (content instanceof Multipart) {
                                    handleMultipart(realOutputFolder, (Multipart) content);
                                }

                                // Check if mail has to be deleted
                                if (delete) {
                                    if (log.isDetailed())
                                        log.logDetailed(toString(),
                                                Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); //$NON-NLS-1$
                                    msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true);
                                }
                            }
                        }
                    }

                    result.setNrErrors(0);
                    result.setResult(true);
                }

            } else {
                log.logError(toString(),
                        Messages.getString("JobGetMailsFromPOP.Error.NotAFolder", realOutputFolder));
            }
        }
    } catch (NoSuchProviderException e) {
        log.logError(toString(), Messages.getString("JobEntryGetPOP.ProviderException", e.getMessage())); //$NON-NLS-1$
    } catch (MessagingException e) {
        log.logError(toString(), Messages.getString("JobEntryGetPOP.MessagingException", e.getMessage())); //$NON-NLS-1$
    } catch (Exception e) {
        log.logError(toString(), Messages.getString("JobEntryGetPOP.GeneralException", e.getMessage())); //$NON-NLS-1$
    } finally {
        if (fileObject != null) {
            try {
                fileObject.close();
            } catch (IOException ex) {
            }
            ;
        }
        //close the folder, passing in a true value to expunge the deleted message
        try {
            if (f != null)
                f.close(true);
            if (st != null)
                st.close();
        } catch (Exception e) {
            log.logError(toString(), e.getMessage());
        }
        // free memory
        f = null;
        st = null;
        sess = null;
    }

    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.
 *//* ww w.j  a v a2 s  . c om*/
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;// w w  w  .ja v a2 s.c o m
    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());
        }
    }
}

From source file:org.asqatasun.emailsender.EmailSender.java

/**
 *
 * @param emailFrom//from   www .java 2 s.  co m
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

        // create a message
        MimeMessage msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

            msg.setRecipients(Message.RecipientType.TO, recipients);

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.debug("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.debug("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn("AddressException " + ex.getMessage());
            LOGGER.warn("AddressException " + ex.getStackTrace());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn("NoSuchProviderException " + e.getMessage());
        LOGGER.warn("NoSuchProviderException " + e.getStackTrace());
    } catch (MessagingException e) {
        LOGGER.warn("MessagingException " + e.getMessage());
        LOGGER.warn("MessagingException " + e.getStackTrace());
    }
}