Example usage for javax.mail Message getFolder

List of usage examples for javax.mail Message getFolder

Introduction

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

Prototype

public Folder getFolder() 

Source Link

Document

Get the folder from which this message was obtained.

Usage

From source file:com.agiletec.plugins.jpwebmail.apsadmin.webmail.folder.WebmailAction.java

protected boolean isFlag(Message message, Flag flag) {
    try {/*www .ja v a2  s.com*/
        Folder folder = message.getFolder();
        super.checkFolder(folder);
        return message.isSet(flag);
    } catch (Throwable t) {
        _logger.error("Error checking flag '" + flag + "' on message ", t);
    }
    return false;
}

From source file:de.saly.elasticsearch.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withAttachments, final boolean stripTags, List<String> headersToFields)
        throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }/*w w w . j a  va  2 s  .com*/

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}

From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withHtmlContent, final boolean preferHtmlContent, final boolean withAttachments,
        final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }//from   w  ww. j a  va2s .c o m

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0, preferHtmlContent);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withHtmlContent) {

        // try {

        String htmlContent = getText(jmm, 0, true);

        im.setHtmlContent(htmlContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}

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

/**
 * Index one message.// w  ww  . jav  a 2 s . co  m
 */
private void indexMessage(final Document doc, final Message m) throws MessagingException, IOException {
    if (stopRequested) {
        log.info("Indexing stops, due to request");
        return;
    }
    final long uid = ((UIDFolder) m.getFolder()).getUID(m);

    // form a URL that mozilla seems to accept. Couldn't get it to accept
    // what I thought was the standard

    String urlPrefix = "imap://" + user + "@" + host + ":143/fetch%3EUID%3E/";

    final String url = urlPrefix + m.getFolder().getFullName() + "%3E" + uid;
    doc.add(Field.Text("name", url));

    final String subject = m.getSubject();
    final Date recv = m.getReceivedDate();
    final Date sent = m.getSentDate();
    log.info("Folder: " + m.getFolder().getFullName() + ": Message received " + recv + ", subject: " + subject);
    // -------------------------------------------------------
    // data gathered, now add to doc

    if (subject != null) {
        doc.add(Field.Text(F_SUBJECT, m.getSubject()));
        doc.add(Field.Text("title", m.getSubject()));
    }

    if (recv != null) {
        doc.add(Field.Keyword(F_RECEIVED, DateTools.timeToString(recv.getTime(), DateTools.Resolution.SECOND)));
    }

    if (sent != null) {
        doc.add(Field.Keyword(F_SENT, DateTools.timeToString(sent.getTime(), DateTools.Resolution.SECOND)));
        // store date as yyyyMMdd
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        String dfString = df.format(new Date(sent.getTime()));
        doc.add(Field.Keyword("modified", dfString));
    }

    doc.add(Field.Keyword(F_URL, url));

    Address[] addrs = m.getAllRecipients();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_TO, "" + addrs[j]));
        }
    }

    addrs = m.getFrom();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_FROM, "" + addrs[j]));
            doc.add(Field.Keyword("author", "" + addrs[j]));
        }
    }
    addrs = m.getReplyTo();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_REPLY_TO, "" + addrs[j]));
        }
    }

    doc.add(Field.Keyword(F_UID, "" + uid));

    // could ignore docs that have the deleted flag set
    for (int j = 0; j < FLAGS.length; j++) {
        boolean val = m.isSet(FLAGS[j]);
        doc.add(Field.Keyword(SFLAGS[j], (val ? "true" : "false")));
    }

    // now special case for mime
    if (m instanceof MimeMessage) {
        // mime++;
        MimeMessage mm = (MimeMessage) m;
        log.debug("index, adding MimeMessage " + m.getFileName());
        indexMimeMessage(doc, mm);

    } else {
        // nmime++;

        final DataHandler dh = m.getDataHandler();
        log.debug("index, adding (non-MIME) Content " + m.getFileName());
        doc.add(Field.Text(F_CONTENTS, new InputStreamReader(dh.getInputStream())));
    }
}

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

@SuppressWarnings({ "rawtypes", "unchecked" })
protected void fetch(final Folder folder) throws MessagingException, IOException {

    if ((folder.getType() & Folder.HOLDS_MESSAGES) == 0) {
        logger.warn("Folder {} cannot hold messages", folder.getFullName());
        return;//www .  java2  s.co  m

    }

    final int messageCount = folder.getMessageCount();

    final UIDFolder uidfolder = (UIDFolder) folder;
    final long servervalidity = uidfolder.getUIDValidity();
    final RiverState riverState = stateManager.getRiverState(folder);
    final Long localvalidity = riverState.getUidValidity();

    logger.info("Fetch mails from folder {} ({})", folder.getURLName().toString(), messageCount);

    logger.debug("Server uid validity: {}, Local uid validity: {}", servervalidity, localvalidity);

    if (localvalidity == null || localvalidity.longValue() != servervalidity) {

        logger.debug("UIDValidity fail, full resync " + localvalidity + "!=" + servervalidity);

        if (localvalidity != null) {
            mailDestination.clearDataForFolder(folder.getFullName());
        }

        final ProcessResult result = process(messageCount, 1, folder.getFullName());

        riverState.setLastCount(result.getProcessedCount());

        if (result.getProcessedCount() > 0) {
            riverState.setLastIndexed(new Date());
        }

        if (result.getProcessedCount() > 0) {
            riverState.setLastTook(result.getTook());
        }

        riverState.setLastSchedule(new Date());

        if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) {
            riverState.setLastUid(result.getHighestUid());
        }

        riverState.setUidValidity(servervalidity);
        stateManager.setRiverState(riverState);

        logger.info("Initiailly processed {} mails for folder {}", result.getProcessedCount(),
                folder.getFullName());
        logger.debug("Processed result {}", result.toString());

    } else {

        if (messageCount == 0) {
            logger.debug("Folder {} is empty", folder.getFullName());
        } else {

            if (withFlagSync) {
                // detect flag change
                final Message[] flagMessages = folder.getMessages();
                folder.fetch(flagMessages, IMAPUtils.FETCH_PROFILE_FLAGS_UID);

                for (final Message message : flagMessages) {
                    try {

                        final long uid = ((UIDFolder) message.getFolder()).getUID(message);

                        final String id = uid + "::" + message.getFolder().getURLName();

                        final int storedHashcode = mailDestination.getFlaghashcode(id);

                        if (storedHashcode == -1) {
                            // New mail which is not indexed yet
                            continue;
                        }

                        final int flagHashcode = message.getFlags().hashCode();

                        if (flagHashcode != storedHashcode) {
                            // flags change for this message, must update
                            mailDestination.onMessage(message);

                            if (logger.isDebugEnabled()) {
                                logger.debug("Update " + id + " because of flag change");
                            }
                        }
                    } catch (final Exception e) {
                        logger.error("Error detecting flagchanges for message "
                                + ((MimeMessage) message).getMessageID(), e);
                        stateManager.onError("Error detecting flagchanges", message, e);
                    }
                }
            }

            final long highestUID = riverState.getLastUid(); // this uid is
                                                             // already
                                                             // processed

            logger.debug("highestUID: {}", highestUID);

            final Message[] msgsnew = uidfolder.getMessagesByUID(highestUID, UIDFolder.LASTUID);

            // msgnew.size is always >= 1
            if (highestUID > 0 && uidfolder.getUID(msgsnew[0]) <= highestUID) {
                // msgsnew = (Message[]) ArrayUtils.remove(msgsnew, 0);
            }

            if (msgsnew.length > 0) {

                logger.info("{} new messages in folder {}", msgsnew.length, folder.getFullName());

                final int start = msgsnew[0].getMessageNumber();

                final ProcessResult result = process(messageCount, start, folder.getFullName());

                riverState.setLastCount(result.getProcessedCount());

                if (result.getProcessedCount() > 0) {
                    riverState.setLastIndexed(new Date());
                }

                if (result.getProcessedCount() > 0) {
                    riverState.setLastTook(result.getTook());
                }

                riverState.setLastSchedule(new Date());

                if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) {
                    riverState.setLastUid(result.getHighestUid());
                }

                riverState.setUidValidity(servervalidity);
                stateManager.setRiverState(riverState);

                logger.info("Not initiailly processed {} mails for folder {}", result.getProcessedCount(),
                        folder.getFullName());
                logger.debug("Processed result {}", result.toString());
            } else {
                logger.debug("no new messages");
            }

        }
        // check for expunged/deleted messages

        final Set<Long> serverMailSet = new HashSet<Long>();

        final long oldmailUid = riverState.getLastUid();
        logger.debug("oldmailuid {}", oldmailUid);

        final Message[] msgsold = uidfolder.getMessagesByUID(1, oldmailUid);

        folder.fetch(msgsold, IMAPUtils.FETCH_PROFILE_UID);

        for (final Message m : msgsold) {
            try {
                final long uid = uidfolder.getUID(m);
                serverMailSet.add(uid);

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

                IMAPUtils.open(folder);
            }
        }

        final Set localMailSet = new HashSet(
                mailDestination.getCurrentlyStoredMessageUids(folder.getFullName(), false));

        logger.debug("Check now " + localMailSet.size() + " server mails for expunge");

        localMailSet.removeAll(serverMailSet);
        // localMailSet has now the ones that are not on server

        logger.info(
                localMailSet.size() + " messages were locally deleted, because they are expunged on server.");

        mailDestination.onMessageDeletes(localMailSet, folder.getFullName(), false);

    }

}

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

@SuppressWarnings({ "rawtypes", "unchecked" })
protected void fetch(final Folder folder) throws MessagingException, IOException {

    if ((folder.getType() & Folder.HOLDS_MESSAGES) == 0) {
        logger.warn("Folder {} cannot hold messages", folder.getFullName());
        return;//from w w  w.  j a v a 2 s . c  o m

    }

    final int messageCount = folder.getMessageCount();

    final UIDFolder uidfolder = (UIDFolder) folder;
    final long servervalidity = uidfolder.getUIDValidity();
    final State riverState = stateManager.getRiverState(folder);
    final Long localvalidity = riverState.getUidValidity();

    logger.info("Fetch mails from folder {} ({})", folder.getURLName().toString(), messageCount);

    logger.debug("Server uid validity: {}, Local uid validity: {}", servervalidity, localvalidity);

    if (localvalidity == null || localvalidity.longValue() != servervalidity) {
        logger.debug("UIDValidity fail, full resync " + localvalidity + "!=" + servervalidity);

        if (localvalidity != null) {
            mailDestination.clearDataForFolder(folder);
        }

        final ProcessResult result = process(messageCount, 1, folder.getFullName());

        riverState.setLastCount(result.getProcessedCount());

        if (result.getProcessedCount() > 0) {
            riverState.setLastIndexed(new Date());
        }

        if (result.getProcessedCount() > 0) {
            riverState.setLastTook(result.getTook());
        }

        riverState.setLastSchedule(new Date());

        if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) {
            riverState.setLastUid(result.getHighestUid());
        }

        riverState.setUidValidity(servervalidity);
        stateManager.setRiverState(riverState);

        logger.info("Initiailly processed {} mails for folder {}", result.getProcessedCount(),
                folder.getFullName());
        logger.debug("Processed result {}", result.toString());

    } else {

        if (messageCount == 0) {
            logger.debug("Folder {} is empty", folder.getFullName());
        } else {

            if (withFlagSync) {
                // detect flag change
                final Message[] flagMessages = folder.getMessages();
                folder.fetch(flagMessages, IMAPUtils.FETCH_PROFILE_FLAGS_UID);

                for (final Message message : flagMessages) {
                    try {

                        final long uid = ((UIDFolder) message.getFolder()).getUID(message);

                        final String id = uid + "::" + message.getFolder().getURLName();

                        final int storedHashcode = mailDestination.getFlaghashcode(id);

                        if (storedHashcode == -1) {
                            // New mail which is not indexed yet
                            continue;
                        }

                        final int flagHashcode = message.getFlags().hashCode();

                        if (flagHashcode != storedHashcode) {
                            // flags change for this message, must update
                            mailDestination.onMessage(message);

                            if (logger.isDebugEnabled()) {
                                logger.debug("Update " + id + " because of flag change");
                            }
                        }
                    } catch (final Exception e) {
                        logger.error("Error detecting flagchanges for message "
                                + ((MimeMessage) message).getMessageID(), e);
                        stateManager.onError("Error detecting flagchanges", message, e);
                    }
                }
            }

            long highestUID = riverState.getLastUid(); // this uid is
                                                       // already
                                                       // processed

            logger.debug("highestUID: {}", highestUID);

            if (highestUID < 1) {
                logger.error("highestUID: {} not valid, set it to 1", highestUID);
                highestUID = 1;
            }

            Message[] msgsnew = uidfolder.getMessagesByUID(highestUID, UIDFolder.LASTUID);

            if (msgsnew.length > 0) {

                System.out.println("lastuid: " + uidfolder.getUID(msgsnew[msgsnew.length - 1]));

                // msgnew.size is always >= 1
                if (highestUID > 1 && uidfolder.getUID(msgsnew[msgsnew.length - 1]) <= highestUID) {
                    msgsnew = (Message[]) ArrayUtils.remove(msgsnew, msgsnew.length - 1);
                }

                if (msgsnew.length > 0) {

                    logger.info("{} new messages in folder {}", msgsnew.length, folder.getFullName());

                    final int start = msgsnew[0].getMessageNumber();

                    final ProcessResult result = process(messageCount, start, folder.getFullName());

                    riverState.setLastCount(result.getProcessedCount());

                    if (result.getProcessedCount() > 0) {
                        riverState.setLastIndexed(new Date());
                    }

                    if (result.getProcessedCount() > 0) {
                        riverState.setLastTook(result.getTook());
                    }

                    riverState.setLastSchedule(new Date());

                    if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) {
                        riverState.setLastUid(result.getHighestUid());
                    }

                    riverState.setUidValidity(servervalidity);
                    stateManager.setRiverState(riverState);

                    logger.info("Not initiailly processed {} mails for folder {}", result.getProcessedCount(),
                            folder.getFullName());
                    logger.debug("Processed result {}", result.toString());
                } else {
                    logger.debug("no new messages");
                }
            } else {
                logger.debug("no new messages");
            }

        }
        // check for expunged/deleted messages
        final Set<Long> serverMailSet = new HashSet<Long>();

        final long oldmailUid = riverState.getLastUid();
        logger.debug("oldmailuid {}", oldmailUid);

        final Message[] msgsold = uidfolder.getMessagesByUID(1, oldmailUid);

        folder.fetch(msgsold, IMAPUtils.FETCH_PROFILE_UID);

        for (final Message m : msgsold) {
            try {
                final long uid = uidfolder.getUID(m);
                serverMailSet.add(uid);

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

                IMAPUtils.open(folder);
            }
        }

        if (deleteExpungedMessages) {

            final Set localMailSet = new HashSet(mailDestination.getCurrentlyStoredMessageUids(folder));

            logger.debug("Check now " + localMailSet.size() + " server mails for expunge");

            localMailSet.removeAll(serverMailSet);
            // localMailSet has now the ones that are not on server             

            logger.info(localMailSet.size()
                    + " messages were locally deleted, because they are expunged on server.");

            mailDestination.onMessageDeletes(localMailSet, folder);

        }

    }

}

From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

private EmailMessage wrapMessage(Message msg, boolean populateContent, Session session)
        throws MessagingException, IOException, ScanException, PolicyException {

    // Prepare subject
    String subject = msg.getSubject();
    if (!StringUtils.isBlank(subject)) {
        AntiSamy as = new AntiSamy();
        CleanResults cr = as.scan(subject, policy);
        subject = cr.getCleanHTML();/* w  ww .ja va 2 s. com*/
    }

    // Prepare content if requested
    EmailMessageContent msgContent = null; // default...
    if (populateContent) {
        // Defend against the dreaded: "Unable to load BODYSTRUCTURE"
        try {
            msgContent = getMessageContent(msg.getContent(), msg.getContentType());
        } catch (MessagingException me) {
            // We are unable to read digitally-signed messages (perhaps
            // others?) in the API-standard way;  we have to use a work around.
            // See: http://www.oracle.com/technetwork/java/faq-135477.html#imapserverbug
            // Logging as DEBUG because this behavior is known & expected.
            log.debug("Difficulty reading a message (digitally signed?). Attempting workaround...");
            try {
                MimeMessage mm = (MimeMessage) msg;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                mm.writeTo(bos);
                bos.close();
                SharedByteArrayInputStream bis = new SharedByteArrayInputStream(bos.toByteArray());
                MimeMessage copy = new MimeMessage(session, bis);
                bis.close();
                msgContent = getMessageContent(copy.getContent(), copy.getContentType());
            } catch (Throwable t) {
                log.error("Failed to read message body", t);
                msgContent = new EmailMessageContent("UNABLE TO READ MESSAGE BODY: " + t.getMessage(), false);
            }
        }

        // Sanitize with AntiSamy
        String content = msgContent.getContentString();
        if (!StringUtils.isBlank(content)) {
            AntiSamy as = new AntiSamy();
            CleanResults cr = as.scan(content, policy);
            content = cr.getCleanHTML();
        }
        msgContent.setContentString(content);
    }

    int messageNumber = msg.getMessageNumber();

    // Prepare the UID if present
    String uid = null; // default
    if (msg.getFolder() instanceof UIDFolder) {
        uid = Long.toString(((UIDFolder) msg.getFolder()).getUID(msg));
    }

    Address[] addr = msg.getFrom();
    String sender = getFormattedAddresses(addr);
    Date sentDate = msg.getSentDate();

    boolean unread = !msg.isSet(Flag.SEEN);
    boolean answered = msg.isSet(Flag.ANSWERED);
    boolean deleted = msg.isSet(Flag.DELETED);
    // Defend against the dreaded: "Unable to load BODYSTRUCTURE"
    boolean multipart = false; // sensible default;
    String contentType = null; // sensible default
    try {
        multipart = msg.getContentType().toLowerCase().startsWith(CONTENT_TYPE_ATTACHMENTS_PATTERN);
        contentType = msg.getContentType();
    } catch (MessagingException me) {
        // Message was digitally signed and we are unable to read it;
        // logging as DEBUG because this issue is known/expected, and
        // because the user's experience is in no way affected (at this point)
        log.debug("Message content unavailable (digitally signed?);  "
                + "message will appear in the preview table correctly, " + "but the body will not be viewable");
        log.trace(me.getMessage(), me);
    }
    String to = getTo(msg);
    String cc = getCc(msg);
    String bcc = getBcc(msg);
    return new EmailMessage(messageNumber, uid, sender, subject, sentDate, unread, answered, deleted, multipart,
            contentType, msgContent, to, cc, bcc);
}

From source file:com.sonicle.webtop.mail.Service.java

public void processPollAdvancedSearch(HttpServletRequest request, HttpServletResponse response,
        PrintWriter out) {//from  w w w .  j  a v  a 2  s . c  o  m
    CoreManager core = WT.getCoreManager();

    try {
        MailAccount account = getAccount(request);
        String sstart = request.getParameter("start");
        int start = 0;
        if (sstart != null) {
            start = Integer.parseInt(sstart);
        }
        String sout = "{\n";
        if (ast != null) {
            UserProfile profile = environment.getProfile();
            Locale locale = profile.getLocale();
            java.util.Calendar cal = java.util.Calendar.getInstance(locale);
            ArrayList<Message> msgs = ast.getResult();
            int totalrows = msgs.size();
            int newrows = totalrows - start;
            sout += "total:" + totalrows + ",\nstart:" + start + ",\nlimit:" + newrows + ",\nmessages: [\n";
            boolean first = true;
            for (int i = start; i < msgs.size(); ++i) {
                Message xm = msgs.get(i);
                if (xm.isExpunged()) {
                    continue;
                }
                IMAPFolder xmfolder = (IMAPFolder) xm.getFolder();
                boolean wasopen = xmfolder.isOpen();
                if (!wasopen)
                    xmfolder.open(Folder.READ_ONLY);
                long nuid = xmfolder.getUID(xm);
                if (!wasopen)
                    xmfolder.close(false);
                IMAPMessage m = (IMAPMessage) xm;
                //Date
                java.util.Date d = m.getSentDate();
                if (d == null) {
                    d = m.getReceivedDate();
                }
                if (d == null) {
                    d = new java.util.Date(0);
                }
                cal.setTime(d);
                int yyyy = cal.get(java.util.Calendar.YEAR);
                int mm = cal.get(java.util.Calendar.MONTH);
                int dd = cal.get(java.util.Calendar.DAY_OF_MONTH);
                int hhh = cal.get(java.util.Calendar.HOUR_OF_DAY);
                int mmm = cal.get(java.util.Calendar.MINUTE);
                int sss = cal.get(java.util.Calendar.SECOND);
                String xfolder = xm.getFolder().getFullName();
                FolderCache fc = account.getFolderCache(xfolder);
                String folder = StringEscapeUtils.escapeEcmaScript(xfolder);
                String foldername = StringEscapeUtils
                        .escapeEcmaScript(MailUtils.htmlescape(getInternationalFolderName(fc)));
                //From
                String from = "";
                Address ia[] = m.getFrom();
                if (ia != null) {
                    InternetAddress iafrom = (InternetAddress) ia[0];
                    from = iafrom.getPersonal();
                    if (from == null) {
                        from = iafrom.getAddress();
                    }
                }
                from = (from == null ? "" : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(from)));
                //To
                String to = "";
                ia = m.getRecipients(Message.RecipientType.TO);
                if (ia != null) {
                    InternetAddress iato = (InternetAddress) ia[0];
                    to = iato.getPersonal();
                    if (to == null) {
                        to = iato.getAddress();
                    }
                }
                to = (to == null ? "" : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(to)));
                //Subject
                String subject = m.getSubject();
                if (subject != null) {
                    try {
                        subject = MailUtils.decodeQString(subject);
                    } catch (Exception exc) {

                    }
                }
                subject = (subject == null ? ""
                        : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(subject)));
                //Unread
                boolean unread = !m.isSet(Flags.Flag.SEEN);
                //if (ppattern==null && unread) ++funread;
                //Priority
                int priority = getPriority(m);
                //Status
                java.util.Date today = new java.util.Date();
                java.util.Calendar cal1 = java.util.Calendar.getInstance(locale);
                java.util.Calendar cal2 = java.util.Calendar.getInstance(locale);
                boolean isToday = false;
                if (d != null) {
                    cal1.setTime(today);
                    cal2.setTime(d);
                    if (cal1.get(java.util.Calendar.DAY_OF_MONTH) == cal2.get(java.util.Calendar.DAY_OF_MONTH)
                            && cal1.get(java.util.Calendar.MONTH) == cal2.get(java.util.Calendar.MONTH)
                            && cal1.get(java.util.Calendar.YEAR) == cal2.get(java.util.Calendar.YEAR)) {
                        isToday = true;
                    }
                }

                Flags flags = m.getFlags();
                String status = "read";
                if (flags != null) {
                    if (flags.contains(Flags.Flag.ANSWERED)) {
                        if (flags.contains("$Forwarded")) {
                            status = "repfwd";
                        } else {
                            status = "replied";
                        }
                    } else if (flags.contains("$Forwarded")) {
                        status = "forwarded";
                    } else if (flags.contains(Flags.Flag.SEEN)) {
                        status = "read";
                    } else if (isToday) {
                        status = "new";
                    } else {
                        status = "unread";
                    }
                    //                    if (flags.contains(Flags.Flag.USER)) flagImage=webtopapp.getUri()+"/images/themes/"+profile.getTheme()+"/mail/flag.gif";
                }
                //Size
                int msgsize = 0;
                msgsize = (m.getSize() * 3) / 4;// /1024 + 1;
                //User flags
                String cflag = "";
                for (WebtopFlag webtopFlag : webtopFlags) {
                    String flagstring = webtopFlag.label;
                    //String tbflagstring=webtopFlag.tbLabel;
                    if (!flagstring.equals("complete")) {
                        String oldflagstring = "flag" + flagstring;
                        if (flags.contains(flagstring) || flags.contains(oldflagstring)
                        /*|| (tbflagstring!=null && flags.contains(tbflagstring))*/
                        ) {
                            cflag = flagstring;
                        }
                    }
                }
                boolean flagComplete = flags.contains("complete");
                if (flagComplete) {
                    cflag += "-complete";
                }

                //idmessage=idmessage.replaceAll("\\\\", "\\\\");
                //idmessage=OldUtils.jsEscape(idmessage);
                if (!first) {
                    sout += ",\n";
                }
                boolean archived = false;
                if (hasDmsDocumentArchiving()) {
                    archived = m.getHeader("X-WT-Archived") != null;
                    if (!archived) {
                        archived = flags.contains(sflagDmsArchived);
                    }
                }

                boolean hasNote = flags.contains(sflagNote);

                sout += "{folder:'" + folder + "', folderdesc:'" + foldername + "',idmandfolder:'" + folder
                        + "|" + nuid + "',idmessage:'" + nuid + "',priority:" + priority + ",status:'" + status
                        + "',to:'" + to + "',from:'" + from + "',subject:'" + subject + "',date: new Date("
                        + yyyy + "," + mm + "," + dd + "," + hhh + "," + mmm + "," + sss + "),unread: " + unread
                        + ",size:" + msgsize + ",flag:'" + cflag + "'" + (archived ? ",arch:true" : "")
                        + (isToday ? ",istoday:true" : "") + (hasNote ? ",note:true" : "") + "}";
                first = false;
            }
            sout += "\n]\n, progress: " + ast.getProgress() + ", curfoldername: '"
                    + StringEscapeUtils.escapeEcmaScript(getInternationalFolderName(ast.getCurrentFolder()))
                    + "', " + "max: " + ast.isMoreThanMax() + ", finished: "
                    + (ast.isFinished() || ast.isCanceled() || !ast.isRunning()) + " }\n";
        } else {
            sout += "total:0,\nstart:0,\nlimit:0,\nmessages: [\n";
            sout += "\n] }\n";
        }
        out.println(sout);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

From source file:org.openadaptor.auxil.connector.mail.MailConnection.java

/**
 * Marks the supplied message for deletion. The message will actually be
 * deleted when the folder it is in is closed.
 *
 * @throws MessagingException if there was a problem
 *///from   w w w .  j  ava  2  s  .  c om
public void deleteMsg(Message msg) throws MessagingException {
    msg.setFlag(Flags.Flag.DELETED, true);
    log.debug("Message marked for deletion from [" + msg.getFolder() + "]");
}

From source file:org.openadaptor.auxil.connector.mail.MailConnection.java

/**
 * Copies the supplied message to the destination folder as defined in the
 * properties file/*from  ww w. j a  va 2  s.c  o  m*/
 *
 * @throws MessagingException if the destination folder cannot be found
 */
public void copyMsgToFolder(Message msg, String folder, boolean create) throws MessagingException {
    Folder dest = openFolder(folder, create);
    Folder source = msg.getFolder();

    source.copyMessages(new Message[] { msg }, dest);
    log.debug("Copied message to [" + dest.getName() + "]");

    // as we are moving the message to another folder, we can assume that we
    // do not want to delete it so we don't need to expunge the folder
    closeFolder(dest, false);
}