Example usage for javax.mail FetchProfile add

List of usage examples for javax.mail FetchProfile add

Introduction

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

Prototype

public void add(String headerName) 

Source Link

Document

Add the specified header-field to the list of attributes to be prefetched.

Usage

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

private void deleteMessagesFromServer(cfSession _Session) throws cfmRunTimeException {

    //--[ Get Message Store
    Store popStore = openConnection(_Session);

    //--[ Open up the Folder:INBOX and retrieve the headers
    Folder popFolder = openFolder(_Session, popStore);

    try {//from w w  w. ja v a 2s. com
        Message[] listOfMessages = popFolder.getMessages();
        FetchProfile fProfile = new FetchProfile();
        fProfile.add(FetchProfile.Item.ENVELOPE);

        if (containsAttribute("UID")) {
            String[] messageUIDList = getMessageUIDList(getDynamic(_Session, "UID").getString());
            fProfile.add(UIDFolder.FetchProfileItem.UID);
            popFolder.fetch(listOfMessages, fProfile);

            for (int x = 0; x < listOfMessages.length; x++) {
                if (messageUIDValid(messageUIDList, getMessageUID(popFolder, listOfMessages[x]))) {
                    listOfMessages[x].setFlag(Flags.Flag.DELETED, true);
                }
            }

        } else if (containsAttribute("MESSAGENUMBER")) {
            int[] messageList = getMessageList(getDynamic(_Session, "MESSAGENUMBER").getString());
            popFolder.fetch(listOfMessages, fProfile);

            for (int x = 0; x < listOfMessages.length; x++) {
                if (messageIDValid(messageList, listOfMessages[x].getMessageNumber())) {
                    listOfMessages[x].setFlag(Flags.Flag.DELETED, true);
                }
            }

        } else {
            throw newRunTimeException(
                    "Either MESSAGENUMBER or UID attribute must be specified when ACTION=DELETE");
        }
    } catch (Exception ignore) {
    }

    //--[ Close off the folder      
    closeFolder(popFolder);
    closeConnection(popStore);
}

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 {/*  www .  j a v a2 s . co 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: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);
    }/*from   w w  w.  j  a  v 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: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);

    for (String PREFETCH_HEADER : PREFETCH_HEADERS) {
        fp.add(PREFETCH_HEADER);/*from  w ww . java 2 s  .  co  m*/
    }
    folder.fetch(msgList, fp);
}

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

public long[] getMessageUIDs(Folder jxFolder, Message[] jxMessages) throws MailException {

    try {/*from   w ww  .  java2  s .  co m*/
        FetchProfile fetchProfile = new FetchProfile();

        fetchProfile.add(UIDFolder.FetchProfileItem.UID);

        jxFolder.fetch(jxMessages, fetchProfile);

        long[] remoteMessageIds = new long[jxMessages.length];

        for (int i = 0; i < jxMessages.length; i++) {
            Message jxMessage = jxMessages[i];

            remoteMessageIds[i] = getUID(jxFolder, jxMessage);
        }

        return remoteMessageIds;
    } catch (MessagingException me) {
        throw new MailException(me);
    }
}

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 ww . j a  v a 2s.co  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:com.liferay.mail.imap.IMAPAccessor.java

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

    Folder jxFolder = null;/*from   w  ww.j av  a2  s  .  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: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);/*ww  w . j  a va2 s . co 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);//from w  w  w  . j  a  v  a2s .  co m
        }
        long endTimeMillis = System.currentTimeMillis();
        log.info("Done fetching headers: " + Util.commatize(endTimeMillis - startTimeMillis) + "ms");
    }
}

From source file:com.funambol.email.items.manager.ImapEntityManager.java

/**
 * get messages from folders./*w w  w .ja v  a2 s.c  o m*/
 * the cache is not filter dependent. This method
 * return all the items in the server without filter
 *
 * @param fullpath path of the folder
 * @param folderId parent id
 * @param filter   EmailFilter
 * @return map with all mail server CrcSyncItemInfo
 * @throws EntityException
 */
private LinkedHashMap getAllEmailsInfoRest(String fullpath, String FID, EmailFilter filter)
        throws EntityException {

    LinkedHashMap syncItemInfos = new LinkedHashMap();
    IMAPFolder f = null;
    Message msg = null;
    long lastCRC = 0;
    String messageID = null;
    java.util.Date headerDate = null;
    String internal = null;
    String internalS = null;
    int itemsNum = 0;
    String GUID = null;
    String FMID = null;
    String UIDV = null;
    EntityException finalExc = null;

    try {

        f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(fullpath);

        // check folder
        if (!f.exists()) {
            return syncItemInfos;
        }

        timeStart = System.currentTimeMillis();

        f.open(Folder.READ_WRITE);

        Message[] items = this.ied.getAllEmails(f, FID, filter);

        // we use a fetch method in the imap protocol (not in the pop)
        if (items != null) {

            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            f.fetch(items, fp);

            // create the info
            itemsNum = items.length;

            for (int i = 0; i < itemsNum; i++) {

                msg = items[i];

                messageID = Utility.getHeaderMessageID(msg);

                try {
                    // REVIEWED THE FILTER TIME STRATEGY
                    //headerDate = UtilityDate.getHeaderDate(msg,null);
                    headerDate = UtilityDate.getDateForTimeFilter(msg, null);
                } catch (Exception e) {
                    log.error("Error parsing header date for Caching System ", e);
                }

                //String dateForCRC = Utility.getHeaderDateForCRC(msg);
                //lastCRC   = Utility.createCRC(msg, messageID, dateForCRC);
                String flagList = Utility.createFlagsList(msg);
                lastCRC = Utility.createCRC(flagList, Def.PROTOCOL_IMAP);

                FMID = String.valueOf(f.getUID(msg));
                UIDV = String.valueOf(f.getUIDValidity());
                GUID = Utility.createIMAPGUID(FID, FMID, UIDV);

                internalS = Utility.getHeaderSyncLabel(msg);
                if (internalS != null) {
                    internal = "Y";
                }

                SyncItemInfo sii = new SyncItemInfo(new SyncItemKey(GUID), lastCRC, messageID, headerDate, null,
                        null, null, null, internal, "Y", null);

                syncItemInfos.put(GUID, sii);

            }

        }

    } catch (MessagingException e) {
        throw new EntityException(e);
    } finally {
        if (f != null) {
            try {
                if (f.isOpen()) {
                    f.close(true);
                    timeStop = System.currentTimeMillis();
                    if (log.isTraceEnabled()) {
                        log.trace("getEmailsInfo Execution Time: " + (timeStop - timeStart) + " ms");
                    }
                }
            } catch (MessagingException me) {
                finalExc = new EntityException(me);
            }
        }
    }

    if (finalExc != null) {
        throw finalExc;
    }

    return syncItemInfos;

}