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.campware.cream.modules.scheduledjobs.Pop3Job.java

private void doReceiveMessages() throws Exception {

    log.debug("Checking mail ");

    String host = Turbine.getConfiguration().getString("mail.pop3.host");
    String username = Turbine.getConfiguration().getString("mail.pop3.user");
    String password = Turbine.getConfiguration().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  .jav a2s . co  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);

    for (int i = 0; i < messages.length; i++) {

        log.debug("Retrieving message " + i);

        // Process each message
        //
        InboxEvent entry = new InboxEvent();
        Address fromAddress = new InternetAddress();
        String from = new String();
        String name = new String();
        String email = new String();
        String replyTo = new String();
        String subject = new String();
        String content = new String();
        Date sentDate = new Date();
        int emailformat = 10;

        Message m = messages[i];

        // and now, handle the content
        Object o = m.getContent();

        // find content type
        if (m.isMimeType("text/plain")) {
            content = "<PRE style=\"font-size: 12px;\">" + (String) o + "</PRE>";
            emailformat = 10;
        } else if (m.isMimeType("text/html")) {
            content = (String) o;
            emailformat = 20;
        } else if (m.isMimeType("text/*")) {
            content = (String) o;
            emailformat = 30;
        } else if (m.isMimeType("multipart/alternative")) {
            try {
                content = handleAlternative(o, content);
                emailformat = 20;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else if (m.isMimeType("multipart/*")) {
            try {
                content = handleMulitipart(o, content, entry);
                emailformat = 40;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else {
            content = "Problem with the message format. Messssage has left on the email server.";
            emailformat = 50;
            log.debug("Could not handle properly");
        }

        email = ((InternetAddress) m.getFrom()[0]).getAddress();
        name = ((InternetAddress) m.getFrom()[0]).getPersonal();
        replyTo = ((InternetAddress) m.getReplyTo()[0]).getAddress();
        sentDate = m.getSentDate();
        subject = m.getSubject();

        log.debug("Got message " + email + " " + name + " " + subject + " " + content);

        Criteria contcrit = new Criteria();
        contcrit.add(ContactPeer.EMAIL, (Object) email, Criteria.EQUAL);
        if (ContactPeer.doSelect(contcrit).size() > 0) {
            log.debug("From known contact");
            Contact myContact = (Contact) ContactPeer.doSelect(contcrit).get(0);
            entry.setCustomerId(myContact.getCustomerId());
            entry.setContactId(myContact.getContactId());
        } else {

            // find if customer exists
            Criteria criteria = new Criteria();
            criteria.add(CustomerPeer.EMAIL, (Object) email, Criteria.EQUAL);
            if (CustomerPeer.doSelect(criteria).size() > 0) {
                log.debug("From known customer");
                Customer myDistrib = (Customer) CustomerPeer.doSelect(criteria).get(0);
                entry.setCustomerId(myDistrib.getCustomerId());
            }

        }

        entry.setInboxEventCode(getTempCode());
        entry.setEventType(10);
        entry.setEventChannel(10);
        entry.setEmailFormat(emailformat);
        entry.setSubject(subject);
        entry.setSenderEmail(email);
        entry.setSenderName(name);
        entry.setSenderReplyTo(replyTo);
        entry.setSentTime(sentDate);
        entry.setBody(content);
        entry.setIssuedDate(new Date());
        entry.setCreatedBy("system");
        entry.setCreated(new Date());
        entry.setModifiedBy("system");
        entry.setModified(new Date());

        Connection conn = Transaction.begin(InboxEventPeer.DATABASE_NAME);
        boolean success = false;
        try {
            entry.save(conn);
            entry.setInboxEventCode(getRowCode("IE", entry.getInboxEventId()));
            entry.save(conn);
            Transaction.commit(conn);
            success = true;
        } finally {
            log.debug("Succcessfully stored in db: " + success);
            if (!success)
                Transaction.safeRollback(conn);
        }

        if (emailformat != 50) {
            m.setFlag(Flags.Flag.DELETED, true);
        }
    }

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

}

From source file:gmailclientfx.controllers.InboxController.java

public void fetchInbox() {
    ObservableList<MyMessage> data = FXCollections.observableArrayList();
    stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId"));
    stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject"));
    stupacPosiljatelj.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender"));
    stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived"));

    Platform.runLater(() -> {/*from ww w  .  ja v  a 2s .c  o  m*/
        inboxTable.setItems(data);
    });
    inboxTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = inboxTable.getSelectionModel().getSelectedItem();
                PregledEmailaHelper.setMsg(selectedMsg);
                try {
                    Parent root;
                    FXMLLoader loader = new FXMLLoader();
                    loader.setLocation(
                            getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml"));
                    root = loader.load();
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root));
                    stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - "
                            + PregledEmailaHelper.getMsg().getSender());
                    stage.show();
                    PregledEmailaController pgec = loader.getController();
                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                        @Override
                        public void handle(WindowEvent event) {
                            pgec.bodyWebViewEngine.load(null);
                            System.out.println("Closing form!");
                        }

                    });
                } catch (IOException ex) {
                    Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    });

    try {
        IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(),
                GmailClient.getAccesToken(), true);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);
        int getSeenCount = inbox.getMessageCount();
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfileItem.FLAGS);
        fp.add(FetchProfileItem.CONTENT_INFO);
        fp.add("X-mailer");

        MimeMessage[] seenMessages = (MimeMessage[]) inbox
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true));
        for (int i = 0; i < seenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "INBOX");
            data.add(msg);
        }

        MimeMessage[] unseenMessages = (MimeMessage[]) inbox
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        for (int i = 0; i < unseenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "INBOX");
            data.add(msg);
        }

        inbox.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.hupa.server.handler.AbstractFetchMessagesHandler.java

protected ArrayList<org.apache.hupa.shared.data.Message> convert(int offset,
        com.sun.mail.imap.IMAPFolder folder, Message[] messages) throws MessagingException {
    ArrayList<org.apache.hupa.shared.data.Message> mList = new ArrayList<org.apache.hupa.shared.data.Message>();
    // Setup fetchprofile to limit the stuff which is fetched 
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);// w w w  .j a v  a2  s.c o  m
    fp.add(FetchProfile.Item.FLAGS);
    fp.add(FetchProfile.Item.CONTENT_INFO);
    fp.add(UIDFolder.FetchProfileItem.UID);
    folder.fetch(messages, fp);

    // loop over the fetched messages
    for (int i = 0; i < messages.length && i < offset; i++) {
        org.apache.hupa.shared.data.Message msg = new org.apache.hupa.shared.data.Message();
        Message m = messages[i];
        String from = null;
        if (m.getFrom() != null && m.getFrom().length > 0) {
            from = MessageUtils.decodeText(m.getFrom()[0].toString());
        }
        msg.setFrom(from);

        String replyto = null;
        if (m.getReplyTo() != null && m.getReplyTo().length > 0) {
            replyto = MessageUtils.decodeText(m.getReplyTo()[0].toString());
        }
        msg.setReplyto(replyto);

        ArrayList<String> to = new ArrayList<String>();
        // Add to addresses
        Address[] toArray = m.getRecipients(RecipientType.TO);
        if (toArray != null) {
            for (Address addr : toArray) {
                String mailTo = MessageUtils.decodeText(addr.toString());
                to.add(mailTo);
            }
        }
        msg.setTo(to);

        // Check if a subject exist and if so decode it
        String subject = m.getSubject();
        if (subject != null) {
            subject = MessageUtils.decodeText(subject);
        }
        msg.setSubject(subject);

        // Add cc addresses
        Address[] ccArray = m.getRecipients(RecipientType.CC);
        ArrayList<String> cc = new ArrayList<String>();
        if (ccArray != null) {
            for (Address addr : ccArray) {
                String mailCc = MessageUtils.decodeText(addr.toString());
                cc.add(mailCc);
            }
        }
        msg.setCc(cc);

        userPreferences.addContact(from);
        userPreferences.addContact(to);
        userPreferences.addContact(replyto);
        userPreferences.addContact(cc);

        // Using sentDate since received date is not useful in the view when using fetchmail
        msg.setReceivedDate(m.getSentDate());

        // Add flags
        ArrayList<IMAPFlag> iFlags = JavamailUtil.convert(m.getFlags());

        ArrayList<Tag> tags = new ArrayList<Tag>();
        for (String flag : m.getFlags().getUserFlags()) {
            if (flag.startsWith(Tag.PREFIX)) {
                tags.add(new Tag(flag.substring(Tag.PREFIX.length())));
            }
        }

        msg.setUid(folder.getUID(m));
        msg.setFlags(iFlags);
        msg.setTags(tags);
        try {
            msg.setHasAttachments(hasAttachment(m));
        } catch (MessagingException e) {
            logger.debug("Unable to identify attachments in message UID:" + msg.getUid() + " subject:"
                    + msg.getSubject() + " cause:" + e.getMessage());
            logger.info("");
        }
        mList.add(0, msg);

    }
    return mList;
}

From source file:org.eurekastreams.server.service.email.ImapEmailIngester.java

/**
 * Ingests email from a mailbox.//ww w.  jav a  2s .  co  m
 */
public void execute() {
    // get message store
    Store store;
    try {
        long startTime = System.nanoTime();
        store = storeFactory.getStore();
        log.debug("Connected to mail store in {}ns", System.nanoTime() - startTime);
    } catch (MessagingException ex) {
        log.error("Error getting message store.", ex);
        return;
    }
    try {
        // get folders
        Folder inputFolder = store.getFolder(inputFolderName);
        if (!inputFolder.exists()) {
            log.error("Input folder {} does not exist.", inputFolderName);
            return;
        }
        Folder successFolder = null;
        if (StringUtils.isNotBlank(successFolderName)) {
            successFolder = store.getFolder(successFolderName);
            if (!successFolder.exists()) {
                log.error("Success folder {} does not exist.", successFolderName);
                return;
            }
        }
        Folder discardFolder = null;
        if (StringUtils.isNotBlank(discardFolderName)) {
            discardFolder = store.getFolder(discardFolderName);
            if (!discardFolder.exists()) {
                log.error("Discard folder {} does not exist.", discardFolderName);
                return;
            }
        }
        Folder errorFolder = null;
        if (StringUtils.isNotBlank(errorFolderName)) {
            errorFolder = store.getFolder(errorFolderName);
            if (!errorFolder.exists()) {
                log.error("Error folder {} does not exist.", errorFolderName);
                return;
            }
        }

        inputFolder.open(Folder.READ_WRITE);

        // fetch messages
        // Note: Not preloading CONTENT_INFO. For some reason, preloading the content info (IMAP BODYSTRUCTURE)
        // causes the call to getContent to return empty. (As if there was a bug where getContent saw the cached
        // body structure and thought that the content itself was cached, but I'd think a bug like that would have
        // been found by many people and fixed long ago, so I'm assuming it's something else.)
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        Message[] msgs = inputFolder.getMessages();
        inputFolder.fetch(msgs, fp);

        log.debug("About to process {} messages", msgs.length);

        // process each message
        if (msgs.length > 0) {
            List<Message> successMessages = new ArrayList<Message>();
            List<Message> errorMessages = new ArrayList<Message>();
            List<Message> discardMessages = new ArrayList<Message>();
            List<Message> responseMessages = new ArrayList<Message>();
            for (int i = 0; i < msgs.length; i++) {
                Message message = msgs[i];
                try {
                    boolean processed = messageProcessor.execute(message, responseMessages);
                    (processed ? successMessages : discardMessages).add(message);
                } catch (Exception ex) {
                    log.error("Failed to process email message.", ex);
                    errorMessages.add(message);
                }
            }

            // send response messages
            for (Message responseMessage : responseMessages) {
                emailerFactory.sendMail(responseMessage);
            }

            // move and purge messages
            if (successFolder != null && !successMessages.isEmpty()) {
                inputFolder.copyMessages(successMessages.toArray(new Message[successMessages.size()]),
                        successFolder);
            }
            if (discardFolder != null && !discardMessages.isEmpty()) {
                inputFolder.copyMessages(discardMessages.toArray(new Message[discardMessages.size()]),
                        discardFolder);
            }
            if (errorFolder != null && !errorMessages.isEmpty()) {
                inputFolder.copyMessages(errorMessages.toArray(new Message[errorMessages.size()]), errorFolder);
            }
            for (int i = 0; i < msgs.length; i++) {
                msgs[i].setFlag(Flag.DELETED, true);
            }

            log.info("{} messages processed:  {} successful, {} discarded, {} failed.", new Object[] {
                    msgs.length, successMessages.size(), discardMessages.size(), errorMessages.size() });
        }

        // close folder
        inputFolder.close(true);
    } catch (MessagingException ex) {
        log.error("Error ingesting email.", ex);
    } catch (Exception ex) {
        log.error("Error ingesting email.", ex);
    } finally {
        // close store
        try {
            store.close();
        } catch (MessagingException ex) {
            log.error("Error closing message store.", ex);
        }
    }
}

From source file:org.springframework.ws.transport.mail.monitor.AbstractMonitoringStrategy.java

/**
 * Fetches the specified messages from the specified folder. Default implementation {@link Folder#fetch(Message[],
 * FetchProfile) fetches} every {@link javax.mail.FetchProfile.Item}.
 *
 * @param folder   the folder to fetch messages from
 * @param messages the messages to fetch
 * @throws MessagingException in case of JavMail errors
 *//* w w w .  j  ava  2 s  . c  om*/
protected void fetchMessages(Folder folder, Message[] messages) throws MessagingException {
    FetchProfile contentsProfile = new FetchProfile();
    contentsProfile.add(FetchProfile.Item.ENVELOPE);
    contentsProfile.add(FetchProfile.Item.CONTENT_INFO);
    contentsProfile.add(FetchProfile.Item.FLAGS);
    folder.fetch(messages, contentsProfile);
}

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

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

    try {//from  w w  w  .j a v  a2 s  .c o  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.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 ww. java 2 s.  c o  m
        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.abid_mujtaba.fetchheaders.models.Account.java

public SparseArray<Email> fetchEmails() throws MessagingException // Fetches messages from account and uses them to create an array of Email objects. Catches connection exception and re-throws them up the chain.
{
    Properties props = new Properties();

    props.setProperty("mail.store.protocol", "imaps");
    props.setProperty("mail.imaps.host", mHost);
    props.setProperty("mail.imaps.port", "993");
    props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // Uses SSL to secure communication
    props.setProperty("mail.imaps.socketFactory.fallback", "false");

    Session imapSession = Session.getInstance(props);

    try {//from   w ww  . j a v  a 2  s .  c  om
        Store store = imapSession.getStore("imaps");

        // Connect to server by sending username and password:
        store.connect(mHost, mUsername, mPassword);

        mInbox = store.getFolder("Inbox");
        mInbox.open(Folder.READ_WRITE); // Open Inbox as read-write since we will be deleting emails later

        mTrash = store.getFolder("Trash");

        if (!mTrash.exists()) {
            mTrash = store.getFolder("[Gmail]/Trash"); // If a folder labelled "Trash" doesn't exist we attempt to check if it is a Gmail account whose trash folder is differently named
            mUsesLabels = true; // Set flag to indicate that this account uses Labels rather than folders a la Gmail

            if (!mTrash.exists()) {
                mTrash = null; // No trash folder found. Emails will be deleted directly
                mUsesLabels = false;
            }
        }

        int num = mInbox.getMessageCount(); // Get number of messages in the Inbox

        if (num > mMaxNumOfEmails) {
            mMessages = mInbox.getMessages(num - mMaxNumOfEmails + 1, num); // Fetch latest mMaxNumOfEmails emails (seen and unseen both). The oldest email is indexed as 1 and so on.
        } else {
            mMessages = mInbox.getMessages();
        }

        FetchProfile fp = new FetchProfile();
        fp.add(IMAPFolder.FetchProfileItem.HEADERS); // Fetch header data
        fp.add(FetchProfile.Item.FLAGS); // Fetch flags

        mInbox.fetch(mMessages, fp);

        // Now that the messages have been fetched using the FetchProfile (that is the necessary information has been fetched with them) we sort the message in reverse chronological order

        Arrays.sort(mMessages, new MessageComparator()); // The sort is accomplished using an instance of a custom comparator that compares messages using DateSent

        mEmails = new SparseArray<Email>();

        for (int ii = 0; ii < mMessages.length; ii++) {
            Email email = new Email(mMessages[ii]);

            mEmails.put(ii, email);
        }

        return mEmails;
    } catch (MessagingException e) {
        Resources.Loge("Exception while attempting to connect to mail server", e);
        throw e;
    } // The two above exceptions are caught by this one if they are not explicitly stated above.
}

From source file:org.nuxeo.ecm.platform.mail.utils.MailCoreHelper.java

protected static void doCheckMail(DocumentModel currentMailFolder, CoreSession coreSession)
        throws MessagingException {
    String email = (String) currentMailFolder.getPropertyValue(EMAIL_PROPERTY_NAME);
    String password = (String) currentMailFolder.getPropertyValue(PASSWORD_PROPERTY_NAME);
    if (!StringUtils.isEmpty(email) && !StringUtils.isEmpty(password)) {
        mailService = getMailService();/*ww  w. j  ava2  s  .co m*/

        MessageActionPipe pipe = mailService.getPipe(PIPE_NAME);

        Visitor visitor = new Visitor(pipe);
        Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader());

        // initialize context
        ExecutionContext initialExecutionContext = new ExecutionContext();

        initialExecutionContext.put(MIMETYPE_SERVICE_KEY, getMimeService());

        initialExecutionContext.put(PARENT_PATH_KEY, currentMailFolder.getPathAsString());

        initialExecutionContext.put(CORE_SESSION_KEY, coreSession);

        initialExecutionContext.put(LEAVE_ON_SERVER_KEY, Boolean.TRUE); // TODO should be an attribute in 'protocol'
                                                                        // schema

        Folder rootFolder = null;
        Store store = null;
        try {
            String protocolType = (String) currentMailFolder.getPropertyValue(PROTOCOL_TYPE_PROPERTY_NAME);
            initialExecutionContext.put(PROTOCOL_TYPE_KEY, protocolType);
            // log.debug(PROTOCOL_TYPE_KEY + ": " + (String) initialExecutionContext.get(PROTOCOL_TYPE_KEY));

            String host = (String) currentMailFolder.getPropertyValue(HOST_PROPERTY_NAME);
            String port = (String) currentMailFolder.getPropertyValue(PORT_PROPERTY_NAME);
            Boolean socketFactoryFallback = (Boolean) currentMailFolder
                    .getPropertyValue(SOCKET_FACTORY_FALLBACK_PROPERTY_NAME);
            String socketFactoryPort = (String) currentMailFolder
                    .getPropertyValue(SOCKET_FACTORY_PORT_PROPERTY_NAME);
            Boolean starttlsEnable = (Boolean) currentMailFolder
                    .getPropertyValue(STARTTLS_ENABLE_PROPERTY_NAME);
            String sslProtocols = (String) currentMailFolder.getPropertyValue(SSL_PROTOCOLS_PROPERTY_NAME);
            Long emailsLimit = (Long) currentMailFolder.getPropertyValue(EMAILS_LIMIT_PROPERTY_NAME);
            long emailsLimitLongValue = emailsLimit == null ? EMAILS_LIMIT_DEFAULT : emailsLimit.longValue();

            String imapDebug = Framework.getProperty(IMAP_DEBUG, "false");

            Properties properties = new Properties();
            properties.put("mail.store.protocol", protocolType);
            // properties.put("mail.host", host);
            // Is IMAP connection
            if (IMAP.equals(protocolType)) {
                properties.put("mail.imap.host", host);
                properties.put("mail.imap.port", port);
                properties.put("mail.imap.starttls.enable", starttlsEnable.toString());
                properties.put("mail.imap.debug", imapDebug);
                properties.put("mail.imap.partialfetch", "false");
            } else if (IMAPS.equals(protocolType)) {
                properties.put("mail.imaps.host", host);
                properties.put("mail.imaps.port", port);
                properties.put("mail.imaps.starttls.enable", starttlsEnable.toString());
                properties.put("mail.imaps.ssl.protocols", sslProtocols);
                properties.put("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                properties.put("mail.imaps.socketFactory.fallback", socketFactoryFallback.toString());
                properties.put("mail.imaps.socketFactory.port", socketFactoryPort);
                properties.put("mail.imap.partialfetch", "false");
                properties.put("mail.imaps.partialfetch", "false");
            } else if (POP3S.equals(protocolType)) {
                properties.put("mail.pop3s.host", host);
                properties.put("mail.pop3s.port", port);
                properties.put("mail.pop3s.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                properties.put("mail.pop3s.socketFactory.fallback", socketFactoryFallback.toString());
                properties.put("mail.pop3s.socketFactory.port", socketFactoryPort);
                properties.put("mail.pop3s.ssl.protocols", sslProtocols);
            } else {
                // Is POP3 connection
                properties.put("mail.pop3.host", host);
                properties.put("mail.pop3.port", port);
            }

            properties.put("user", email);
            properties.put("password", password);

            Session session = Session.getInstance(properties);

            store = session.getStore();
            store.connect(email, password);

            String folderName = INBOX; // TODO should be an attribute in 'protocol' schema
            rootFolder = store.getFolder(folderName);

            // need RW access to update message flags
            rootFolder.open(Folder.READ_WRITE);

            Message[] allMessages = rootFolder.getMessages();
            // VDU
            log.debug("nbr of messages in folder:" + allMessages.length);

            FetchProfile fetchProfile = new FetchProfile();
            fetchProfile.add(FetchProfile.Item.FLAGS);
            fetchProfile.add(FetchProfile.Item.ENVELOPE);
            fetchProfile.add(FetchProfile.Item.CONTENT_INFO);
            fetchProfile.add("Message-ID");
            fetchProfile.add("Content-Transfer-Encoding");

            rootFolder.fetch(allMessages, fetchProfile);

            if (rootFolder instanceof IMAPFolder) {
                // ((IMAPFolder)rootFolder).doCommand(FetchProfile)
            }

            List<Message> unreadMessagesList = new ArrayList<Message>();
            for (Message message : allMessages) {
                Flags flags = message.getFlags();
                int unreadMessagesListSize = unreadMessagesList.size();
                if (flags != null && !flags.contains(Flag.SEEN)
                        && unreadMessagesListSize < emailsLimitLongValue) {
                    unreadMessagesList.add(message);
                    if (unreadMessagesListSize == emailsLimitLongValue - 1) {
                        break;
                    }
                }
            }

            Message[] unreadMessagesArray = unreadMessagesList.toArray(new Message[unreadMessagesList.size()]);

            // perform email import
            visitor.visit(unreadMessagesArray, initialExecutionContext);

            // perform flag update globally
            Flags flags = new Flags();
            flags.add(Flag.SEEN);

            boolean leaveOnServer = (Boolean) initialExecutionContext.get(LEAVE_ON_SERVER_KEY);
            if ((IMAP.equals(protocolType) || IMAPS.equals(protocolType)) && leaveOnServer) {
                flags.add(Flag.SEEN);
            } else {
                flags.add(Flag.DELETED);
            }
            rootFolder.setFlags(unreadMessagesArray, flags, true);

        } finally {
            if (rootFolder != null && rootFolder.isOpen()) {
                rootFolder.close(true);
            }
            if (store != null) {
                store.close();
            }
        }
    }
}

From source file:org.springframework.integration.mail.AbstractMailReceiver.java

/**
 * Fetches the specified messages from this receiver's folder. Default
 * implementation {@link Folder#fetch(Message[], FetchProfile) fetches}
 * every {@link javax.mail.FetchProfile.Item}.
 *
 * @param messages the messages to fetch
 * @throws MessagingException in case of JavaMail errors
 *///  w  w  w.jav  a 2 s . c om
protected void fetchMessages(Message[] messages) throws MessagingException {
    FetchProfile contentsProfile = new FetchProfile();
    contentsProfile.add(FetchProfile.Item.ENVELOPE);
    contentsProfile.add(FetchProfile.Item.CONTENT_INFO);
    contentsProfile.add(FetchProfile.Item.FLAGS);
    this.folder.fetch(messages, contentsProfile);
}