Example usage for javax.mail FetchProfile FetchProfile

List of usage examples for javax.mail FetchProfile FetchProfile

Introduction

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

Prototype

public FetchProfile() 

Source Link

Document

Create an empty FetchProfile.

Usage

From source file:org.exist.xquery.modules.mail.MessageListFunctions.java

private void prefetchMessages(Folder folder, Message[] msgList) throws MessagingException {
    // Prefetch all the key information and headers

    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);//from   www  .  j  a  v a  2 s  .  c om

    for (String PREFETCH_HEADER : PREFETCH_HEADERS) {
        fp.add(PREFETCH_HEADER);
    }
    folder.fetch(msgList, fp);
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

public void storeContents(long folderId, long[] remoteMessageIds) throws IOException, PortalException {

    Folder jxFolder = null;/*from   w ww . j  a  v a  2s.co  m*/

    try {
        jxFolder = openFolder(folderId);

        Message[] jxMessages = getMessagesByUID(jxFolder, remoteMessageIds);

        FetchProfile fetchProfile = new FetchProfile();

        fetchProfile.add(UIDFolder.FetchProfileItem.CONTENT_INFO);
        fetchProfile.add(UIDFolder.FetchProfileItem.FLAGS);
        fetchProfile.add(UIDFolder.FetchProfileItem.UID);

        jxFolder.fetch(jxMessages, fetchProfile);

        for (Message jxMessage : jxMessages) {
            String flags = getFlags(jxMessage);

            long remoteMessageId = getUID(jxFolder, jxMessage);

            com.liferay.mail.model.Message message = MessageLocalServiceUtil.getMessage(folderId,
                    remoteMessageId);

            StringBundler bodyPlain = new StringBundler();
            StringBundler bodyHtml = new StringBundler();
            List<MailFile> mailFiles = new ArrayList<>();

            getParts(_user.getUserId(), bodyPlain, bodyHtml, StringPool.BLANK, jxMessage, mailFiles);

            if (bodyHtml.length() == 0) {
                if (bodyPlain.length() == 0) {
                    bodyHtml.append("&nbsp;");
                } else {
                    bodyHtml = bodyPlain;
                }
            }

            if (flags.indexOf(MailConstants.FLAG_SEEN) == -1) {
                jxMessage.setFlag(Flags.Flag.SEEN, false);
            }

            AttachmentLocalServiceUtil.deleteAttachments(message.getCompanyId(), message.getMessageId());

            for (MailFile mailFile : mailFiles) {
                AttachmentLocalServiceUtil.addAttachment(_user.getUserId(), message.getMessageId(),
                        mailFile.getContentPath(), mailFile.getFileName(), mailFile.getSize(),
                        mailFile.getFile());
            }

            MessageLocalServiceUtil.updateContent(message.getMessageId(), bodyHtml.toString(), flags);
        }
    } catch (MessagingException me) {
        throw new MailException(me);
    } finally {
        closeFolder(jxFolder, false);
    }
}

From source file:com.naryx.tagfusion.cfm.mail.cfPOP3.java

private void readMessages(cfSession _Session, Folder popFolder, cfQueryResultData popData, int _start, int _max,
        boolean GetAll, File attachmentDir) throws cfmRunTimeException {
    try {//  w  w w.  j a  v  a 2 s .  c o  m
        int maxRows = _max;
        int startRow = _start;
        String messageNumber = getDynamic(_Session, "MESSAGENUMBER").getString();
        boolean containsUID = containsAttribute("UID");
        boolean usingMessageNumber = messageNumber.length() > 0;
        int msgCount = popFolder.getMessageCount();

        // if MAXROWS is not specified, or UID or MESSAGENUMBER is, then we want to get all the messages
        if (_max == -1 || containsUID || usingMessageNumber) {
            maxRows = msgCount;
        }
        if (containsUID || usingMessageNumber) {
            startRow = 1;
        }

        if (msgCount != 0 && startRow > msgCount) {
            throw newRunTimeException(
                    "The value of STARTROW must not be greater than the total number of messages in the folder, "
                            + popFolder.getMessageCount() + ".");
        }

        Message[] listOfMessages;
        if (!usingMessageNumber) {
            listOfMessages = popFolder.getMessages();
        } else {
            listOfMessages = popFolder.getMessages(getMessageList(messageNumber));
        }

        FetchProfile fProfile = new FetchProfile();
        fProfile.add(FetchProfile.Item.ENVELOPE);
        fProfile.add(UIDFolder.FetchProfileItem.UID);
        popFolder.fetch(listOfMessages, fProfile);

        if (containsUID) {
            String[] messageUIDList = getMessageUIDList(getDynamic(_Session, "UID").getString());

            for (int x = 0; x < listOfMessages.length; x++) {
                if (messageUIDList.length == 0
                        || messageUIDValid(messageUIDList, getMessageUID(popFolder, listOfMessages[x]))) {
                    populateMessage(_Session, listOfMessages[x], popData, GetAll, attachmentDir, popFolder);
                }
            }
        } else {
            popFolder.fetch(listOfMessages, fProfile);
            int end = startRow - 1 + maxRows;
            if (end > listOfMessages.length) {
                end = listOfMessages.length;
            }
            for (int x = startRow - 1; x < end; x++) {
                populateMessage(_Session, listOfMessages[x], popData, GetAll, attachmentDir, popFolder);
            }
        }
    } catch (Exception E) {
        if (E.getMessage() != null)
            throw newRunTimeException(E.getMessage());
        else
            throw newRunTimeException(E.toString());
    }

}

From source file:com.cubusmail.server.mail.util.MessageUtils.java

/**
 * @param complete//w w  w .j  a  va  2  s  . c  o m
 * @param sortfield
 * @return
 */
public static FetchProfile createFetchProfile(boolean complete, MessageListFields sortfield) {

    FetchProfile fp = new FetchProfile();
    if (complete) {
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfile.Item.FLAGS);
        fp.add(FetchProfile.Item.CONTENT_INFO);
        fp.add(IMAPFolder.FetchProfileItem.SIZE);
        fp.add(CubusConstants.FETCH_ITEM_PRIORITY);
        fp.add(UIDFolder.FetchProfileItem.UID);
    } else {
        if (sortfield != null) {
            if (MessageListFields.SUBJECT == sortfield || MessageListFields.FROM == sortfield
                    || MessageListFields.TO == sortfield || MessageListFields.SEND_DATE == sortfield) {
                fp.add(FetchProfile.Item.ENVELOPE);
            } else if (MessageListFields.SIZE == sortfield) {
                fp.add(IMAPFolder.FetchProfileItem.SIZE);
            }
        }
    }
    return fp;
}

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

/**
 * Create a Message List.//  w  ww  .ja  v  a 2 s  .  co 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:com.liferay.mail.imap.IMAPAccessor.java

public void storeEnvelopes(long folderId, Folder jxFolder, Message[] jxMessages) throws PortalException {

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();/*  w w w .j a  v a 2s .c  o m*/

    try {
        FetchProfile fetchProfile = new FetchProfile();

        fetchProfile.add(UIDFolder.FetchProfileItem.ENVELOPE);
        fetchProfile.add(UIDFolder.FetchProfileItem.FLAGS);
        fetchProfile.add(UIDFolder.FetchProfileItem.UID);

        jxFolder.fetch(jxMessages, fetchProfile);

        for (Message jxMessage : jxMessages) {
            String sender = InternetAddressUtil.toString(jxMessage.getFrom());
            String to = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.TO));
            String cc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.CC));
            String bcc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.BCC));
            Date sentDate = jxMessage.getSentDate();
            String subject = jxMessage.getSubject();
            String flags = getFlags(jxMessage);
            long remoteMessageId = getUID(jxFolder, jxMessage);
            String contentType = jxMessage.getContentType();

            try {
                MessageLocalServiceUtil.getMessage(folderId, remoteMessageId);
            } catch (NoSuchMessageException nsme) {
                MessageLocalServiceUtil.addMessage(_user.getUserId(), folderId, sender, to, cc, bcc, sentDate,
                        subject, StringPool.BLANK, flags, remoteMessageId, contentType);
            }
        }

        com.liferay.mail.model.Folder folder = FolderLocalServiceUtil.getFolder(folderId);

        FolderLocalServiceUtil.updateFolder(folderId, folder.getFullName(), folder.getDisplayName(),
                jxFolder.getMessageCount());
    } catch (MessagingException me) {
        throw new MailException(me);
    }

    if (_log.isDebugEnabled()) {
        stopWatch.stop();

        _log.debug("Downloaded " + jxMessages.length + " messages from folder " + jxFolder.getFullName()
                + " completed in " + stopWatch.getTime() + " ms");
    }
}

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

private List<EmailMessage> getEmailMessages(Folder mailFolder, int pageStart, int messageCount, Session session)
        throws MessagingException, IOException, ScanException, PolicyException {

    int totalMessageCount = mailFolder.getMessageCount();
    int start = Math.max(1, totalMessageCount - pageStart - (messageCount - 1));
    int end = Math.max(totalMessageCount - pageStart, 1);

    Message[] messages = totalMessageCount != 0 ? mailFolder.getMessages(start, end) : new Message[0];

    long startTime = System.currentTimeMillis();

    // Fetch only necessary headers for each message
    FetchProfile profile = new FetchProfile();
    profile.add(FetchProfile.Item.ENVELOPE);
    profile.add(FetchProfile.Item.FLAGS);
    profile.add(FetchProfile.Item.CONTENT_INFO);
    if (mailFolder instanceof UIDFolder) {
        profile.add(UIDFolder.FetchProfileItem.UID);
    }/*w w  w.j  av a2 s  .co m*/
    mailFolder.fetch(messages, profile);

    if (log.isDebugEnabled()) {
        log.debug("Time elapsed while fetching message headers; {}ms", System.currentTimeMillis() - startTime);
    }

    List<EmailMessage> emails = new LinkedList<EmailMessage>();
    for (Message currentMessage : messages) {
        EmailMessage emailMessage = wrapMessage(currentMessage, false, session);
        emails.add(emailMessage);
    }

    Collections.reverse(emails);
    return emails;
}

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * @param complete//ww w .j a v a 2 s. c  o  m
 * @param sortfield
 * @return
 */
public static FetchProfile createFetchProfile(boolean complete, String sortfield) {

    FetchProfile fp = new FetchProfile();
    if (complete) {
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfile.Item.FLAGS);
        fp.add(FetchProfile.Item.CONTENT_INFO);
        fp.add(IMAPFolder.FetchProfileItem.SIZE);
        fp.add(CubusConstants.FETCH_ITEM_PRIORITY);
        fp.add(UIDFolder.FetchProfileItem.UID);
    } else {
        if (sortfield != null) {
            if (MessageListFields.ATTACHMENT_FLAG.name().equals(sortfield)) {
                fp.add(FetchProfile.Item.CONTENT_INFO);
            } else if (MessageListFields.SUBJECT.name().equals(sortfield)
                    || MessageListFields.FROM.name().equals(sortfield)
                    || MessageListFields.TO.name().equals(sortfield)
                    || MessageListFields.DATE.name().equals(sortfield)) {
                fp.add(FetchProfile.Item.ENVELOPE);
            } else if (MessageListFields.SIZE.name().equals(sortfield)) {
                fp.add(IMAPFolder.FetchProfileItem.SIZE);
            }
        }
    }
    return fp;
}

From source file:edu.stanford.muse.email.EmailFetcherStats.java

private void fetchHeaders(Message[] messages) throws MessagingException {
    // fetch headers (don't do it for mbox folders, waste of time)
    // this is an essential perf. step so that we fetch the headers in bulk.
    // otherwise it takes a long time to fetch header info one at a time for each message
    if (!(emailStore instanceof MboxEmailStore)) {
        long startTimeMillis = System.currentTimeMillis();
        currentStatus = JSONUtils.getStatusJSON("Reading headers from " + folder.getName() + "...");
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfile.Item.CONTENT_INFO);
        fp.add(UIDFolder.FetchProfileItem.UID); // important, otherwise reading UIDs takes a long time later
        fp.add("List-Post");
        folder.fetch(messages, fp);//from  w  ww . j a v  a 2s  . c o  m
        long endTimeMillis = System.currentTimeMillis();
        log.info("Done fetching headers: " + Util.commatize(endTimeMillis - startTimeMillis) + "ms");
    }
}

From source file:edu.stanford.muse.email.EmailFetcherStats.java

private void fetchHeaders(int nMessages) throws MessagingException {
    // fetch headers (don't do it for mbox folders, waste of time)
    // this is an essential perf. step so that we fetch the headers in bulk.
    // otherwise it takes a long time to fetch header info one at a time for each message
    if (!(emailStore instanceof MboxEmailStore)) {
        long startTimeMillis = System.currentTimeMillis();
        currentStatus = JSONUtils.getStatusJSON("Reading headers from " + folder.getName() + "...");
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfile.Item.CONTENT_INFO);
        fp.add(UIDFolder.FetchProfileItem.UID); // important, otherwise reading UIDs takes a long time later
        fp.add("List-Post");
        for (int i = 0; i < nMessages; i++) {
            Message[] messages = new Message[] { folder.getMessage(i) };
            folder.fetch(messages, fp);/*w  w  w .  j  a va  2 s .  c  o m*/
        }
        long endTimeMillis = System.currentTimeMillis();
        log.info("Done fetching headers: " + Util.commatize(endTimeMillis - startTimeMillis) + "ms");
    }
}