Example usage for javax.mail Folder READ_ONLY

List of usage examples for javax.mail Folder READ_ONLY

Introduction

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

Prototype

int READ_ONLY

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

Click Source Link

Document

The Folder is read only.

Usage

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

@RequestMapping(value = "/EajaxtestNoL", method = RequestMethod.GET)
public @ResponseBody String ajaxtestNoL(Principal principal) {
    String name = principal.getName();
    String result = "";
    try {/*w w  w  .  ja v  a  2s .c  o  m*/
        users u = usuarioService.getByLogin(name);

        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");

        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

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

        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        Calendar fecha3 = Calendar.getInstance();
        fecha3.roll(Calendar.MONTH, false);
        Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime()));
        //Message msg[] = inbox.search(ft);
        System.out.println("MAILS: " + msg.length);
        for (Message message : msg) {
            try {
                /*System.out.println("DATE: "+message.getSentDate().toString());
                System.out.println("FROM: "+message.getFrom()[0].toString());            
                System.out.println("SUBJECT: "+message.getSubject().toString());
                System.out.println("CONTENT: "+message.getContent().toString());
                System.out.println("******************************************");
                */result = result + "<li>" + "<a href='#' class='clearfix'>" + "<span class='msg-body'>"
                        + "<span class='msg-title'>" + "<span class='blue'>" + message.getFrom()[0].toString()
                        + "</span>" +

                        message.getSubject().toString() + "</span>" +

                        "</span>" + "</a>" + "</li> ";
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("No Information");
            }
        }

    } catch (Exception ex) {
    }

    return result;
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Create a Message List.//from  w ww  .  j  a  v a2 s .c  om
 * Fetches a list of headers in folder foldername for part list_part.
 * The messagelist will be stored in the "MESSAGES" environment.
 *
 * @param foldername folder for which a message list should be built
 * @param list_part part of list to display (1 = last xx messages, 2 = total-2*xx - total-xx messages)
 */
public void createMessageList(String folderhash, int list_part) throws NoSuchFolderException {
    long time_start = System.currentTimeMillis();
    TimeZone tz = TimeZone.getDefault();
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
            user.getPreferredLocale());
    df.setTimeZone(tz);

    try {
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);
        Element xml_current = model.setCurrentFolder(folderhash);
        Element xml_messagelist = model.getMessageList(xml_folder);

        if (folder == null) {
            throw new NoSuchFolderException(folderhash);
        }

        long fetch_start = System.currentTimeMillis();

        if (!folder.isOpen()) {
            folder.open(Folder.READ_ONLY);
        } else {
            folder.close(false);
            folder.open(Folder.READ_ONLY);
        }

        /* Calculate first and last message to show */
        int total_messages = folder.getMessageCount();
        int new_messages = folder.getNewMessageCount();
        int show_msgs = user.getMaxShowMessages();

        xml_messagelist.setAttribute("total", total_messages + "");
        xml_messagelist.setAttribute("new", new_messages + "");

        log.debug("Total: " + total_messages);

        /* Handle small messagelists correctly */
        if (total_messages < show_msgs) {
            show_msgs = total_messages;
        }
        /* Don't accept list-parts smaller than 1 */
        if (list_part < 1) {
            list_part = 1;
        }
        for (int k = 0; k < list_part; k++) {
            total_messages -= show_msgs;
        }
        /* Handle beginning of message list */
        if (total_messages < 0) {
            total_messages = 0;
        }
        int first = total_messages + 1;
        int last = total_messages + show_msgs;
        /* Set environment variable */
        setEnv();
        xml_current.setAttribute("first_msg", first + "");
        xml_current.setAttribute("last_msg", last + "");
        xml_current.setAttribute("list_part", list_part + "");

        /* Fetch headers */
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfile.Item.FLAGS);
        fp.add(FetchProfile.Item.CONTENT_INFO);
        log.debug("Last: " + last + ", first: " + first);
        Message[] msgs = folder.getMessages(first, last);
        log.debug(msgs.length + " messages fetching...");
        folder.fetch(msgs, fp);
        long fetch_stop = System.currentTimeMillis();

        Map header = new Hashtable(15);

        Flags.Flag[] sf;
        String from, to, cc, bcc, replyto, subject;
        String messageid;

        for (int i = msgs.length - 1; i >= 0; i--) {
            //              if(((MimeMessage)msgs[i]).getMessageID() == null) {
            //                  folder.close(false);
            //                  folder.open(Folder.READ_WRITE);
            //                  ((MimeMessage)msgs[i]).setHeader("Message-ID","<"+user.getLogin()+"."+System.currentTimeMillis()+".jwebmail@"+user.getDomain()+">");
            //                  ((MimeMessage)msgs[i]).saveChanges();
            //                  folder.close(false);
            //                  folder.open(Folder.READ_ONLY);
            //              }

            try {
                StringTokenizer tok = new StringTokenizer(((MimeMessage) msgs[i]).getMessageID(), "<>");
                messageid = tok.nextToken();
            } catch (NullPointerException ex) {
                // For mail servers that don't generate a Message-ID (Outlook et al)
                messageid = user.getLogin() + "." + i + ".jwebmail@" + user.getDomain();
            }

            XMLMessage xml_message = model.getMessage(xml_folder, msgs[i].getMessageNumber() + "", messageid);

            /* Addresses */
            from = "";
            replyto = "";
            to = "";
            cc = "";
            bcc = "";
            try {
                from = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getFrom()));
            } catch (UnsupportedEncodingException e) {
                from = Helper.joinAddress(msgs[i].getFrom());
            }
            try {
                replyto = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getReplyTo()));
            } catch (UnsupportedEncodingException e) {
                replyto = Helper.joinAddress(msgs[i].getReplyTo());
            }
            try {
                to = MimeUtility
                        .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO)));
            } catch (UnsupportedEncodingException e) {
                to = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO));
            }
            try {
                cc = MimeUtility
                        .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC)));
            } catch (UnsupportedEncodingException e) {
                cc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC));
            }
            try {
                bcc = MimeUtility
                        .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC)));
            } catch (UnsupportedEncodingException e) {
                bcc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC));
            }
            if (from == "")
                from = getStringResource("unknown sender");
            if (to == "")
                to = getStringResource("unknown recipient");

            /* Flags */
            sf = msgs[i].getFlags().getSystemFlags();
            String basepath = parent.getBasePath();

            for (int j = 0; j < sf.length; j++) {
                if (sf[j] == Flags.Flag.RECENT)
                    xml_message.setAttribute("recent", "true");
                if (sf[j] == Flags.Flag.SEEN)
                    xml_message.setAttribute("seen", "true");
                if (sf[j] == Flags.Flag.DELETED)
                    xml_message.setAttribute("deleted", "true");
                if (sf[j] == Flags.Flag.ANSWERED)
                    xml_message.setAttribute("answered", "true");
                if (sf[j] == Flags.Flag.DRAFT)
                    xml_message.setAttribute("draft", "true");
                if (sf[j] == Flags.Flag.FLAGGED)
                    xml_message.setAttribute("flagged", "true");
                if (sf[j] == Flags.Flag.USER)
                    xml_message.setAttribute("user", "true");
            }
            if (msgs[i] instanceof MimeMessage
                    && ((MimeMessage) msgs[i]).getContentType().toUpperCase().startsWith("MULTIPART/")) {
                xml_message.setAttribute("attachment", "true");
            }

            if (msgs[i] instanceof MimeMessage) {
                int size = ((MimeMessage) msgs[i]).getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");
            }

            /* Subject */
            subject = "";
            if (msgs[i].getSubject() != null) {
                try {
                    subject = MimeUtility.decodeText(msgs[i].getSubject());
                } catch (UnsupportedEncodingException ex) {
                    subject = msgs[i].getSubject();
                    log.warn("Unsupported Encoding: " + ex.getMessage());
                }
            }
            if (subject == null || subject.equals("")) {
                subject = getStringResource("no subject");
            }

            /* Set all of what we found into the DOM */
            xml_message.setHeader("FROM", from);
            try {
                // hmm, why decode subject twice? Though it doesn't matter..
                xml_message.setHeader("SUBJECT", MimeUtility.decodeText(subject));
            } catch (UnsupportedEncodingException e) {
                xml_message.setHeader("SUBJECT", subject);
                log.warn("Unsupported Encoding: " + e.getMessage());
            }
            xml_message.setHeader("TO", to);
            xml_message.setHeader("CC", cc);
            xml_message.setHeader("BCC", bcc);
            xml_message.setHeader("REPLY-TO", replyto);

            /* Date */
            Date d = msgs[i].getSentDate();
            String ds = "";
            if (d != null) {
                ds = df.format(d);
            }
            xml_message.setHeader("DATE", ds);
        }
        long time_stop = System.currentTimeMillis();
        // try {
        // XMLCommon.writeXML(model.getRoot(),new FileOutputStream("/tmp/wmdebug"),"");
        // } catch(IOException ex) {}

        log.debug("Construction of message list took " + (time_stop - time_start)
                + " ms. Time for IMAP transfer was " + (fetch_stop - fetch_start) + " ms.");
        folder.close(false);
    } catch (NullPointerException e) {
        log.error("Failed to construct message list", e);
        throw new NoSuchFolderException(folderhash);
    } catch (MessagingException ex) {
        log.error("Failed to construct message list.  " + "For some reason, contuing anyways.", ex);
    }
}

From source file:com.intranet.intr.inbox.SupControllerInbox.java

@RequestMapping(value = "/ajaxtestNoL", method = RequestMethod.GET)
public @ResponseBody String ajaxtestNoL(Principal principal) {
    String name = principal.getName();
    String result = "";
    try {//from   w  w  w .j  av a2 s  .co m
        users u = usuarioService.getByLogin(name);

        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");

        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

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

        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        Calendar fecha3 = Calendar.getInstance();
        fecha3.roll(Calendar.MONTH, false);
        Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime()));
        //Message msg[] = inbox.search(ft);
        System.out.println("MAILS: " + msg.length);
        for (Message message : msg) {
            try {
                /*System.out.println("DATE: "+message.getSentDate().toString());
                System.out.println("FROM: "+message.getFrom()[0].toString());            
                System.out.println("SUBJECT: "+message.getSubject().toString());
                System.out.println("CONTENT: "+message.getContent().toString());
                System.out.println("******************************************");
                */result = result + "<li>" + "<a href='#' class='clearfix'>" + "<span class='msg-body'>"
                        + "<span class='msg-title'>" + "<span class='blue'>" + message.getFrom()[0].toString()
                        + "</span>" +

                        message.getSubject().toString() + "</span>" +

                        "</span>" + "</a>" + "</li> ";
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("No Information");
            }
        }

    } catch (Exception ex) {
    }

    return result;
}

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);/* w  ww.jav  a 2  s. co 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:org.usergrid.rest.management.RegistrationIT.java

private Message[] getMessages(String host, String user, String password)
        throws MessagingException, IOException {

    Session session = Session.getDefaultInstance(new Properties());
    Store store = session.getStore("imap");
    store.connect(host, user, password);

    Folder folder = store.getFolder("inbox");
    folder.open(Folder.READ_ONLY);
    Message[] msgs = folder.getMessages();

    for (Message m : msgs) {
        logger.info("Subject: " + m.getSubject());
        logger.info("Body content 0 " + (String) ((MimeMultipart) m.getContent()).getBodyPart(0).getContent());
        logger.info("Body content 1 " + (String) ((MimeMultipart) m.getContent()).getBodyPart(1).getContent());
    }//from  ww  w . j a v  a 2s .  c o  m
    return msgs;
}

From source file:org.apache.usergrid.rest.management.RegistrationIT.java

private Message[] getMessages(String host, String user, String password)
        throws MessagingException, IOException {

    Session session = Session.getDefaultInstance(new Properties());
    Store store = session.getStore("imap");
    store.connect(host, user, password);

    Folder folder = store.getFolder("inbox");
    folder.open(Folder.READ_ONLY);
    Message[] msgs = folder.getMessages();

    for (Message m : msgs) {
        logger.info("Subject: " + m.getSubject());
        logger.info("Body content 0 " + ((MimeMultipart) m.getContent()).getBodyPart(0).getContent());
        logger.info("Body content 1 " + ((MimeMultipart) m.getContent()).getBodyPart(1).getContent());
    }/*from w  ww  . jav a  2  s .c  o m*/
    return msgs;
}

From source file:org.pentaho.di.job.entries.getpop.MailConnection.java

/**
 * Open the folder.//  w ww  .  j a va  2  s. c  om
 *
 * @param foldername
 *          the name of the folder to open
 * @param defaultFolder
 *          true to open the default folder (INBOX)
 * @param write
 *          open the folder in write mode
 * @throws KettleException
 *           if something went wrong.
 */
public void openFolder(String foldername, boolean defaultFolder, boolean write) throws KettleException {
    this.write = write;
    try {
        if (getFolder() != null) {
            // A folder is already opened
            // before make sure to close it
            closeFolder(true);
        }

        if (defaultFolder) {
            if (protocol == MailConnectionMeta.PROTOCOL_MBOX) {
                this.folder = this.store.getDefaultFolder();
            } else {
                // get the default folder
                this.folder = getRecursiveFolder(MailConnectionMeta.INBOX_FOLDER);
            }

            if (this.folder == null) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "JobGetMailsFromPOP.InvalidDefaultFolder.Label"));
            }

            if ((folder.getType() & Folder.HOLDS_MESSAGES) == 0) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "MailConnection.DefaultFolderCanNotHoldMessage"));
            }
        } else {
            // Open specified Folder (for IMAP/MBOX)
            if (this.protocol == MailConnectionMeta.PROTOCOL_IMAP
                    || this.protocol == MailConnectionMeta.PROTOCOL_MBOX) {
                this.folder = getRecursiveFolder(foldername);
            }
            if (this.folder == null || !this.folder.exists()) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "JobGetMailsFromPOP.InvalidFolder.Label"));
            }
        }
        if (this.write) {
            if (log.isDebug()) {
                log.logDebug(BaseMessages.getString(PKG, "MailConnection.OpeningFolderInWriteMode.Label",
                        getFolderName()));
            }
            this.folder.open(Folder.READ_WRITE);
        } else {
            if (log.isDebug()) {
                log.logDebug(BaseMessages.getString(PKG, "MailConnection.OpeningFolderInReadMode.Label",
                        getFolderName()));
            }
            this.folder.open(Folder.READ_ONLY);
        }

        if (log.isDetailed()) {
            log.logDetailed(
                    BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.Label", getFolderName()));
        }
        if (log.isDebug()) {
            // display some infos on folder
            //CHECKSTYLE:LineLength:OFF
            log.logDebug(BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.Name", getFolderName()));
            log.logDebug(BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.FullName",
                    this.folder.getFullName()));
            log.logDebug(BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.Url",
                    this.folder.getURLName().toString()));
            log.logDebug(BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.Subscribed",
                    "" + this.folder.isSubscribed()));
        }

    } catch (Exception e) {
        throw new KettleException(
                defaultFolder ? BaseMessages.getString(PKG, "JobGetMailsFromPOP.Error.OpeningDefaultFolder")
                        : BaseMessages.getString(PKG, "JobGetMailsFromPOP.Error.OpeningFolder", foldername),
                e);
    }
}

From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java

protected int fetchFolder(IMAPFolder folder, EmailFolder repoFolder, boolean topFlag)
        throws MessagingException {
    int n = 0;/*from   w  w w . j  ava 2  s.  c o  m*/
    if (!topFlag) {
        if (logger.isDebugEnabled())
            logger.debug("Openning folder " + folder.getName());
        folder.open(Folder.READ_ONLY);
        List<EmailMessage> fetchedEmails = repoFolder.getEmails();
        long firstUID = 1;
        if (fetchedEmails.size() > 0) {
            firstUID = fetchedEmails.get(fetchedEmails.size() - 1).getUID() + 1;
        }
        Message[] messages = folder.getMessagesByUID(firstUID, UIDFolder.LASTUID);
        n = messages.length;
        for (int i = 0; i < messages.length; i++) {
            AlvexEmailMessage m = new AlvexEmailMessage((MimeMessage) messages[i], folder);
            if (m.getUID() < firstUID)
                continue;
            if (logger.isDebugEnabled())
                logger.debug("Fetched message " + Integer.toString((i + 1)) + "/"
                        + Integer.toString(messages.length) + " from folder " + folder.getName() + ": \""
                        + m.getSubject() + "\" from " + m.getFrom());
            Map<QName, Serializable> props = new HashMap<QName, Serializable>();
            props.put(AlvexContentModel.PROP_EMAIL_FROM, m.getFrom());
            props.put(AlvexContentModel.PROP_EMAIL_TO, m.getTo());
            props.put(AlvexContentModel.PROP_EMAIL_CC, (Serializable) m.getCC());
            props.put(AlvexContentModel.PROP_EMAIL_SUBJECT, m.getSubject());
            props.put(AlvexContentModel.PROP_EMAIL_IN_REPLY_TO, m.getInReplyTo());
            props.put(AlvexContentModel.PROP_EMAIL_SENT_DATE, m.getSentDate());
            props.put(AlvexContentModel.PROP_EMAIL_UID, m.getUID());
            props.put(AlvexContentModel.PROP_EMAIL_ID, m.getID());
            NodeRef messageNode = createNode(repoFolder.getNodeRef(), ContentModel.ASSOC_CONTAINS,
                    AlvexContentModel.TYPE_EMAIL_MESSAGE, props);
            writeContent(messageNode, m.getBody());
            for (EmailMessagePart att : m.getAttachments()) {
                // FIXME_ASAP: think about it more carefully
                String subj = m.getSubject();
                String fname = att.getFileName();
                if (fname.equals(subj + " (part 1).html"))
                    continue;
                if (logger.isDebugEnabled())
                    logger.debug("Creating attachment: " + att.getFileName());
                props.clear();
                props.put(AlvexContentModel.PROP_EMAIL_REAL_NAME, att.getFileName());
                // FIXME_ASAP: think about it more carefully
                props.put(ContentModel.PROP_NAME, att.getFileName());
                NodeRef attNodeRef = createNode(messageNode, AlvexContentModel.ASSOC_EMAIL_ATTACHMENTS,
                        AlvexContentModel.TYPE_EMAIL_ATTACHMENT, props);
                writeContent(attNodeRef, att);
            }
            for (EmailMessageEventListener l : listeners)
                if (l != null)
                    l.onNewMessageReceived(new EmailMessageImpl(messageNode, nodeService, contentService));
        }
        if (logger.isDebugEnabled())
            logger.debug("Closing folder " + folder.getName());
        folder.close(true);
    }
    for (EmailFolder f : repoFolder.getSubfolders())
        if (f.isFetchActive()) {
            fetchFolder((IMAPFolder) folder.getFolder(f.getName()), f, false);
        }
    return n;
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void dontTestMessageCache() throws Exception {

    // Create messages
    NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE);
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();//from  w  w  w. j a v a2  s .  c o m

    // Create messages more than cache capacity
    for (int i = 0; i < 51; i++) {
        FileInfo fi = fileFolderService.create(nodeService.getParentAssocs(contentNode).get(0).getParentRef(),
                "test" + i, ContentModel.TYPE_CONTENT);
        ContentWriter writer = fileFolderService.getWriter(fi.getNodeRef());
        writer.putContent("test");
    }

    txn.commit();

    // Reload folder
    folder.close(false);
    folder = (IMAPFolder) store.getFolder(TEST_FOLDER);
    folder.open(Folder.READ_ONLY);

    // Read all messages
    for (int i = 1; i < 51; i++) {
        // Get test message UID
        final Long uid = getMessageUid(folder, i);
        // Get Message size
        final int count = getMessageSize(folder, uid);

        // Get first part
        BODY body = getMessageBodyPart(folder, uid, 0, count - 100);
        // Read second message part
        BODY bodyRest = getMessageBodyPart(folder, uid, count - 100, 100);

        // Creating and parsing message from 2 parts
        MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()),
                new SequenceInputStream(new BufferedInputStream(body.getByteArrayInputStream()),
                        new BufferedInputStream(bodyRest.getByteArrayInputStream())));

        // Reading first part - should be successful
        MimeMultipart content = (MimeMultipart) message.getContent();
        assertNotNull(content.getBodyPart(0).getContent());
        assertNotNull(content.getBodyPart(1).getContent());
    }
}

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);//from w w w  .jav  a  2s  .  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;
}