Example usage for javax.mail Folder close

List of usage examples for javax.mail Folder close

Introduction

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

Prototype

public abstract void close(boolean expunge) throws MessagingException;

Source Link

Document

Close this Folder.

Usage

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

public void testMailbox() {
    logger.info("Getting folder...");
    long t = System.currentTimeMillis();

    // Create empty properties
    Properties props = new Properties();
    props.setProperty("mail.imap.partialfetch", "false");

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

    Store store = null;/*from w  w  w .  j av a 2  s .  co m*/
    Folder folder = null;
    try {
        // Get the store
        store = session.getStore("imap");
        store.connect(REMOTE_HOST, USER_NAME, USER_PASSWORD);

        // Get folder
        folder = store.getFolder(TEST_FOLDER_NAME);
        folder.open(Folder.READ_ONLY);

        // Get directory
        Message message[] = folder.getMessages();

        for (int i = 0, n = message.length; i < n; i++) {
            message[i].getAllHeaders();

            Address[] from = message[i].getFrom();
            System.out.print(i + ": ");
            if (from != null) {
                System.out.print(message[i].getFrom()[0] + "\t");
            }
            System.out.println(message[i].getSubject());

            Object content = message[i].getContent();
            if (content instanceof MimeMultipart) {
                for (int j = 0, m = ((MimeMultipart) content).getCount(); j < m; j++) {
                    BodyPart part = ((MimeMultipart) content).getBodyPart(j);
                    Object partContent = part.getContent();

                    if (partContent instanceof String) {
                        String body = (String) partContent;
                    } else if (partContent instanceof FilterInputStream) {
                        FilterInputStream fis = (FilterInputStream) partContent;
                        BufferedInputStream bis = new BufferedInputStream(fis);

                        /* while (bis.available() > 0) 
                         {
                            bis.read();
                         }*/
                        byte[] bytes = new byte[524288];
                        while (bis.read(bytes) != -1) {
                        }
                        bis.close();
                        fis.close();
                    }
                }
            }

            int nn = 0;

        }

        t = System.currentTimeMillis() - t;
        logger.info("Time: " + t + " ms (" + t / 1000 + " s)");
        logger.info("Length: " + message.length);

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    } finally {
        // Close connection
        try {
            if (folder != null) {
                folder.close(false);
            }
        } catch (MessagingException e) {
            logger.error(e.getMessage(), e);
            fail(e.getMessage());
        }
        try {
            if (store != null) {
                store.close();
            }
        } catch (MessagingException e) {
            logger.error(e.getMessage(), e);
            fail(e.getMessage());
        }
    }

}

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

/**
 * Fetch a message from a folder./*from  w  w w  . j a v a 2 s.  c o m*/
 * Will put the messages parameters in the sessions environment
 *
 * @param foldername Name of the folder were the message should be fetched from
 * @param msgnum Number of the message to fetch
 * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message
 *             into the current work element of the user and set some additional flags on the message if the user
 *             has enabled this option.
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD
 */
public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException {
    // security reasons:
    // attachments=null;

    try {
        TimeZone tz = TimeZone.getDefault();
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
                user.getPreferredLocale());
        df.setTimeZone(tz);
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);

        if (folder == null) {
            throw new NoSuchFolderException("No such folder: " + folderhash);
        }

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

        MimeMessage m = (MimeMessage) folder.getMessage(msgnum);

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

        Element xml_current = model.setCurrentMessage(messageid);
        XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid);

        /* Check whether we already cached this message (not only headers but complete)*/
        boolean cached = xml_message.messageCompletelyCached();
        /* If we cached the message, we don't need to fetch it again */
        if (!cached) {
            //Element xml_header=model.getHeader(xml_message);

            try {
                String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom()));
                String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo()));
                String to = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO)));
                String cc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC)));
                String bcc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC)));
                Date date_orig = m.getSentDate();
                String date = getStringResource("no date");
                if (date_orig != null) {
                    date = df.format(date_orig);
                }
                String subject = "";
                if (m.getSubject() != null) {
                    subject = MimeUtility.decodeText(m.getSubject());
                }
                if (subject == null || subject.equals("")) {
                    subject = getStringResource("no subject");
                }

                try {
                    Flags.Flag[] sf = m.getFlags().getSystemFlags();
                    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");
                    }
                } catch (NullPointerException ex) {
                }
                if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) {
                    xml_message.setAttribute("attachment", "true");
                }

                int size = m.getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");

                /* Set all of what we found into the DOM */
                xml_message.setHeader("FROM", from);
                xml_message.setHeader("SUBJECT", Fancyfier.apply(subject));
                xml_message.setHeader("TO", to);
                xml_message.setHeader("CC", cc);
                xml_message.setHeader("BCC", bcc);
                xml_message.setHeader("REPLY-TO", replyto);
                xml_message.setHeader("DATE", date);

                /* Decode MIME contents recursively */
                xml_message.removeAllParts();
                parseMIMEContent(m, xml_message, messageid);

            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage());
            }
        }
        /* Set seen flag (Maybe make that threaded to improve performance) */
        if (user.wantsSetFlags()) {
            if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) {
                folder.close(false);
                folder.open(Folder.READ_WRITE);
            } else if (!folder.isOpen()) {
                folder.open(Folder.READ_WRITE);
            }
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true);
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false);
            if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true);
            }
        }
        folder.close(false);

        /* In this part we determine whether the message was requested so that it may be used for
           further editing (replying or forwarding). In this case we set the current "work" message to the
           message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */
        XMLMessage work = null;
        if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY
                || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
            log.debug("Setting work message!");
            work = model.setWorkMessage(xml_message);

            String newmsgid = WebMailServer.generateMessageID(user.getUserName());

            if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", from);
                work.prepareReply(getStringResource("reply subject prefix"),
                        getStringResource("reply subject postfix"), getStringResource("reply message prefix"),
                        getStringResource("reply message postfix"));

            } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", "");
                work.setHeader("CC", "");
                work.prepareForward(getStringResource("forward subject prefix"),
                        getStringResource("forward subject postfix"),
                        getStringResource("forward message prefix"),
                        getStringResource("forward message postfix"));

                /* Copy all references to MIME parts to the new message id */
                for (String key : getMimeParts(work.getAttribute("msgid"))) {
                    StringTokenizer tok2 = new StringTokenizer(key, "/");
                    tok2.nextToken();
                    String newkey = tok2.nextToken();
                    mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key));
                }
            }

            /* Clear the msgnr and msgid fields at last */
            work.setAttribute("msgnr", "0");
            work.setAttribute("msgid", newmsgid);
            prepareCompose();
        }
    } catch (MessagingException ex) {
        log.error("Failed to get message.  Doing nothing instead.", ex);
    }
}

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

/**
 * Import messages// w w w.  j  a  v  a  2  s  .  c  om
 * 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  www.  j  av  a  2 s  .c  om
 * 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:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

@Override
public EmailMessage getMessage(MailStoreConfiguration config, String messageId) {
    Authenticator auth = credentialsProvider.getAuthenticator();
    Folder inbox = null;
    try {//ww  w  . j  a  va2 s. c  o m
        int mode = config.getMarkMessagesAsRead() ? Folder.READ_WRITE : Folder.READ_ONLY;

        // Retrieve user's inbox
        Session session = openMailSession(config, auth);
        inbox = getUserInbox(session, config.getInboxFolderName());
        inbox.open(mode);

        Message message;
        if (inbox instanceof UIDFolder) {
            message = ((UIDFolder) inbox).getMessageByUID(Long.parseLong(messageId));
        } else {
            message = inbox.getMessage(Integer.parseInt(messageId));
        }
        boolean unread = !message.isSet(Flags.Flag.SEEN);
        if (config.getMarkMessagesAsRead()) {
            message.setFlag(Flag.SEEN, true);
        }
        EmailMessage emailMessage = wrapMessage(message, true, session);
        if (!config.getMarkMessagesAsRead()) {
            // NOTE:  This is more than a little bit annoying.  Apparently
            // the mere act of accessing the body content of a message in
            // Javamail flags the in-memory representation of that message
            // as SEEN.  It does *nothing* to the mail server (the message
            // is still unread in the SOR), but it wreaks havoc on local
            // functions that key off that value and expect it to be
            // accurate.  We're obligated, therefore, to restore the value
            // to what it was before the call to wrapMessage().
            emailMessage.setUnread(unread);
        }

        return emailMessage;
    } catch (MessagingException e) {
        log.error("Messaging exception while retrieving individual message", e);
    } catch (IOException e) {
        log.error("IO exception while retrieving individual message", e);
    } catch (ScanException e) {
        log.error("AntiSamy scanning exception while retrieving individual message", e);
    } catch (PolicyException e) {
        log.error("AntiSamy policy exception while retrieving individual message", e);
    } finally {
        if (inbox != null) {
            try {
                inbox.close(false);
            } catch (Exception e) {
                log.warn("Can't close correctly javamail inbox connection");
            }
            try {
                inbox.getStore().close();
            } catch (Exception e) {
                log.warn("Can't close correctly javamail store connection");
            }
        }
    }

    return null;
}

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

private void doReceiveMessages() throws Exception {

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

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

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

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

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

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

    // Open read-only
    folder.open(Folder.READ_WRITE);/*from   w ww .j a  v  a2s.  c  o  m*/

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

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

        DinboxEvent entry = new DinboxEvent();

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

        entry.setDinboxEventCode(getTempCode());

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

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

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

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

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

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

}

From source file:org.zilverline.core.IMAPCollection.java

private final boolean indexFolder(IndexWriter writer, Folder thisFolder) throws MessagingException {
    if (stopRequested) {
        log.info("Indexing stops, due to request");
        return false;
    }//from   www  .  j a  va 2 s.  c om
    if ((thisFolder.getType() & Folder.HOLDS_MESSAGES) != 0) {
        thisFolder.open(Folder.READ_ONLY);
        Message[] messages = thisFolder.getMessages(); // get refs to all msgs
        if (messages == null) {
            // dummy
            messages = new Message[0];
        }

        thisFolder.fetch(messages, PROFILE); // fetch headers

        log.debug("FOLDER: " + thisFolder.getFullName() + " messages=" + messages.length);

        for (int i = 0; i < messages.length; i++) {
            try {
                String msgID = null;
                if (messages[i] instanceof MimeMessage) {
                    MimeMessage mm = (MimeMessage) messages[i];
                    msgID = mm.getMessageID();
                }
                if (!md5DocumentCache.contains(msgID)) {
                    log.debug("new message added for message: " + msgID);
                    final Document doc = new Document();
                    doc.add(Field.Keyword(F_FOLDER, thisFolder.getFullName()));
                    doc.add(Field.Keyword("collection", name));
                    // index this message
                    indexMessage(doc, messages[i]);
                    // add it
                    writer.addDocument(doc);
                    md5DocumentCache.add(msgID);
                } else {
                    log.debug("existing message skipped for message: " + msgID);
                }
            } catch (Exception ioe) {
                // can be side effect of hosed up mail headers
                log.warn("Bad Message: " + messages[i], ioe);
                continue;
            }
        }

    }
    // recurse if possible
    if ((thisFolder.getType() & Folder.HOLDS_FOLDERS) != 0) {
        Folder[] far = thisFolder.list();
        if (far != null) {
            for (int i = 0; i < far.length; i++) {
                indexFolder(writer, far[i]);
            }
        }
    }
    if (thisFolder.isOpen()) {
        log.debug("Closing folder: " + thisFolder.getFullName());
        thisFolder.close(false); // false => do not expunge
    }

    return true;
}

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

/**
 * Create a Message List./*w w  w. j  av  a2 s .  c  o  m*/
 * 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:net.wastl.webmail.server.WebMailSession.java

public void refreshFolderInformation(String folderhash) {
    Folder folder = getFolder(folderhash);
    Element xml_folder = model.getFolder(folderhash);

    if (xml_folder.getAttribute("holds_messages").toLowerCase().equals("true")) {
        try {/*from  ww w  .  j a va 2  s .  c o m*/
            Element messagelist = model.createMessageList();

            int total_messages = folder.getMessageCount();
            int new_messages = folder.getNewMessageCount();

            if ((total_messages == -1 || new_messages == -1) && !folder.isOpen()) {
                folder.open(Folder.READ_ONLY);
                total_messages = folder.getMessageCount();
                new_messages = folder.getNewMessageCount();
            }
            if (folder.isOpen())
                folder.close(false);

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

            model.removeMessageList(xml_folder);
            xml_folder.appendChild(messagelist);

        } catch (MessagingException ex) {
            xml_folder.setAttribute("error", ex.getMessage());
        }
    }
}

From source file:server.MailPop3Expert.java

@Override
public void run() {
    //obtengo la agenda
    List<String> agenda = XmlParcerExpert.getInstance().getAgenda();

    while (store.isConnected()) {
        try {//from   ww w  . ja  v a 2  s  .  c  o  m

            // Abre la carpeta INBOX
            Folder folderInbox = store.getFolder("INBOX");
            folderInbox.open(Folder.READ_ONLY);

            // Obtiene los mails
            Message[] arrayMessages = folderInbox.getMessages();

            //procesa los mails
            for (int i = 0; i < arrayMessages.length; i++) {
                Message message = arrayMessages[i];
                Address[] fromAddress = message.getFrom();
                String from = fromAddress[0].toString();
                String subject = message.getSubject();
                String sentDate = message.getSentDate().toString();
                String messageContent = "";
                String contentType = message.getContentType();

                if (contentType.contains("multipart")) {
                    // Si el contenido es mulpart
                    Multipart multiPart = (Multipart) message.getContent();
                    int numberOfParts = multiPart.getCount();
                    for (int partCount = 0; partCount < numberOfParts; partCount++) {
                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                            // si contiene un archivo
                        } else {
                            // el contenido del mensaje
                            messageContent = part.getContent().toString();
                        }
                    }

                } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                    Object content = message.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                }

                //parseo del from
                if (from.contains("<")) {
                    from = from.substring(from.indexOf("<") + 1, from.length() - 1);
                }

                //si esta en la agenda
                if (agenda.contains(from)) {
                    //obtiene la trama
                    try {
                        messageContent = messageContent.substring(messageContent.indexOf("&gt"),
                                messageContent.indexOf("&lt;") + 4);
                        if (messageContent.startsWith("&gt") && messageContent.endsWith("&lt;")) {
                            //procesa el mail
                            XmlParcerExpert.getInstance().processAndSaveMail(from, messageContent);
                            frame.loadMails();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    //no lo guarda
                }

            }

            folderInbox.close(false);

            //duerme el hilo por el tiempo de la frecuencia
            Thread.sleep(frecuency * 60 * 1000);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException ex) {
            //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}