Example usage for javax.mail Folder getMessages

List of usage examples for javax.mail Folder getMessages

Introduction

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

Prototype

public synchronized Message[] getMessages() throws MessagingException 

Source Link

Document

Get all Message objects from this Folder.

Usage

From source file:com.szmslab.quickjavamail.receive.MailReceiver.java

/**
 * ????/*from  w w w.jav  a  2s  .  co m*/
 *
 * @param callback
 *            ??1???
 * @throws Exception
 */
public void execute(ReceiveIterationCallback callback) throws Exception {
    final Session session = useDefaultSession
            ? Session.getDefaultInstance(properties.getProperties(), properties.getAuthenticator())
            : Session.getInstance(properties.getProperties(), properties.getAuthenticator());
    session.setDebug(isDebug);

    Store store = null;
    Folder folder = null;
    try {
        store = session.getStore(properties.getProtocol());
        store.connect();

        folder = store.getFolder(folderName);
        folder.open(readonly ? Folder.READ_ONLY : Folder.READ_WRITE);

        final Message messages[] = folder.getMessages();
        for (Message message : messages) {
            MessageLoader loader = new MessageLoader(message, !readonly);
            boolean isContinued = callback.iterate(loader);
            if (!readonly && loader.isDeleted()) {
                message.setFlag(Flags.Flag.DELETED, loader.isDeleted());
            }
            if (!isContinued) {
                break;
            }
        }
    } finally {
        if (folder != null) {
            try {
                folder.close(!readonly);
            } catch (MessagingException e) {
                System.out.println(e);
            }
        }
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                System.out.println(e);
            }
        }
    }
}

From source file:org.syncope.core.notification.NotificationTest.java

private boolean verifyMail(final String sender, final String subject) {
    LOG.info("Waiting for notification to be sent...");
    try {/* w  w  w. j  a v a2s . co  m*/
        Thread.sleep(10000);
    } catch (InterruptedException e) {
    }

    boolean found = false;
    try {
        Session session = Session.getDefaultInstance(System.getProperties());
        Store store = session.getStore("pop3");
        store.connect(pop3Host, mailAddress, mailPassword);

        Folder inbox = store.getFolder("INBOX");
        assertNotNull(inbox);
        inbox.open(Folder.READ_WRITE);

        Message[] messages = inbox.getMessages();
        for (int i = 0; i < messages.length; i++) {
            if (sender.equals(messages[i].getFrom()[0].toString())
                    && subject.equals(messages[i].getSubject())) {

                found = true;
                messages[i].setFlag(Flag.DELETED, true);
            }
        }
        inbox.close(true);
        store.close();
    } catch (Throwable t) {
        LOG.error("Unexpected exception", t);
        fail("Unexpected exception while fetching e-mail");
    }

    return found;
}

From source file:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java

public void downloadEmails(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword) throws IOException {

    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);/*from w w w.  j  a v a2  s.  com*/
    try {
        // connects to the message store
        Store store = session.getStore(mailStoreProtocol);
        store.connect(mailStoreHost, mailStoreUserName, mailStorePassword);

        logger.info("connected to message store");

        // opens the inbox folder
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_ONLY);

        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String from = fromAddress[0].toString();
            String subject = msg.getSubject();
            String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
            String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
            String sentDate = msg.getSentDate().toString();

            String contentType = msg.getContentType();
            String messageContent = "";

            if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                try {
                    Object content = msg.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                } catch (Exception ex) {
                    messageContent = "[Error downloading content]";
                    ex.printStackTrace();
                }
            }

            // print out details of each message
            System.out.println("Message #" + (i + 1) + ":");
            System.out.println("\t From: " + from);
            System.out.println("\t To: " + toList);
            System.out.println("\t CC: " + ccList);
            System.out.println("\t Subject: " + subject);
            System.out.println("\t Sent Date: " + sentDate);
            System.out.println("\t Message: " + messageContent);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        logger.warn("No provider for protocol: " + mailStoreProtocol + " " + ex);
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store" + ex);
    }
}

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

private void doReceiveMessages() throws Exception {

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

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

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

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

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

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

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

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

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

        DinboxEvent entry = new DinboxEvent();

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

        entry.setDinboxEventCode(getTempCode());

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

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

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

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

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

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

}

From source file:server.MailPop3Expert.java

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

    while (store.isConnected()) {
        try {//from   w w w.j a  va2  s  .  co  m

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

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

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

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

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

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

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

            }

            folderInbox.close(false);

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

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

}

From source file:com.seleniumtests.connectors.mails.ImapClient.java

/**
 * get list of all emails in folder//  ww  w.j a  va 2 s. co m
 * 
 * @param folderName      folder to read
 * @param firstMessageTime   date from which we should get messages
 * @param firstMessageIndex index of the firste message to find
 * @throws MessagingException
 * @throws IOException
 */
@Override
public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime)
        throws MessagingException, IOException {

    if (folderName == null) {
        throw new MessagingException("folder ne doit pas tre vide");
    }

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

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

    List<Message> preFilteredMessages = new ArrayList<>();

    final LocalDateTime firstTime = firstMessageTime;

    // on filtre les message en fonction du mode de recherche
    if (searchMode == SearchMode.BY_INDEX || firstTime == null) {
        for (int i = firstMessageIndex, n = messages.length; i < n; i++) {
            preFilteredMessages.add(messages[i]);
        }
    } else {
        preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean match(Message msg) {
                try {
                    return !msg.getReceivedDate()
                            .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant()));
                } catch (MessagingException e) {
                    return false;
                }
            }
        }));

    }

    List<Email> filteredEmails = new ArrayList<>();
    lastMessageIndex = messages.length;

    for (Message message : preFilteredMessages) {

        String contentType = "";
        try {
            contentType = message.getContentType();
        } catch (MessagingException e) {
            MimeMessage msg = (MimeMessage) message;
            message = new MimeMessage(msg);
            contentType = message.getContentType();
        }

        // decode content
        String messageContent = "";
        List<String> attachments = new ArrayList<>();

        if (contentType.toLowerCase().contains("text/html")) {
            messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString());
        } else if (contentType.toLowerCase().contains("multipart/")) {
            List<BodyPart> partList = getMessageParts((Multipart) message.getContent());

            // store content in list
            for (BodyPart part : partList) {

                String partContentType = part.getContentType().toLowerCase();
                if (partContentType.contains("text/html")) {
                    messageContent = messageContent
                            .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString()));

                } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) {
                    messageContent = messageContent.concat((String) part.getContent().toString());

                } else if (partContentType.contains("image") || partContentType.contains("application/")
                        || partContentType.contains("text/x-vcard")) {
                    if (part.getFileName() != null) {
                        attachments.add(part.getFileName());
                    } else {
                        attachments.add(part.getDescription());
                    }
                } else {
                    logger.debug("type: " + part.getContentType());
                }
            }
        }

        // create a new email
        filteredEmails.add(new Email(message.getSubject(), messageContent, "",
                message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(),
                attachments));
    }

    folder.close(false);

    return filteredEmails;
}

From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java

/**
 * {@inheritDoc}//from   w ww  .  j ava  2  s  . com
 * 
 * @see org.xwiki.contrib.mail.IMailReader#readFromStore(java.lang.String)
 */
@Override
public List<Message> read(String folder, boolean onlyUnred, int max) throws MessagingException {
    Store store = getJavamailStore();
    store.connect();
    Folder mailFolder = store.getDefaultFolder();
    if (StringUtils.isNotEmpty(folder)) {
        mailFolder = mailFolder.getFolder(folder);
    }
    mailFolder.open(Folder.READ_WRITE);
    Message[] msgsArray = mailFolder.getMessages();
    if (max > 0 && msgsArray.length > max) {
        msgsArray = (Message[]) ArrayUtils.subarray(msgsArray, 0, max);
    }
    List<Message> messages = new ArrayList<Message>(Arrays.asList(msgsArray));
    mailFolder.close(false);
    store.close();
    return messages;
}

From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java

/**
 * Returns new messages and fetches details for each message.
 *//*from   ww  w .  jav  a  2 s.  co m*/
@Transactional(readOnly = false)
public ResultClass<Boolean> downloadEmails() {

    ResultClass<Boolean> result = new ResultClass<>();
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);

    try {

        // connects to the message store
        Store store = session.getStore(protocol);

        store.connect(userName, password);
        // opens the inbox folder
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_ONLY);
        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();
        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];

            String[] idHeaders = msg.getHeader("MESSAGE-ID");
            if (idHeaders != null && idHeaders.length > 0) {

                MessageBox exists = repositoryMailBox.getMessageBox(idHeaders[0]);
                if (exists == null) {

                    MessageBox messageBox = new MessageBox();
                    messageBox.setSubject(msg.getSubject());
                    messageBox.setCode(idHeaders[0]);

                    Address[] fromAddresses = msg.getFrom();
                    String from = InternetAddress.toString(fromAddresses);

                    if (from.startsWith("=?")) {
                        from = MimeUtility.decodeWord(from);
                    }
                    messageBox.setFrom(from);
                    String to = InternetAddress.toString(msg.getRecipients(RecipientType.TO));

                    if (to.startsWith("=?")) {
                        to = MimeUtility.decodeWord(to);
                    }
                    messageBox.setTo(to);

                    String[] replyHeaders = msg.getHeader("References");

                    if (replyHeaders != null && replyHeaders.length > 0) {
                        StringTokenizer tokens = new StringTokenizer(replyHeaders[0]);
                        MessageBox parent = repositoryMailBox.getMessageBox(tokens.nextToken());
                        if (parent != null)
                            parent.addReply(messageBox);
                    }

                    result = parseSubjectAndCreate(messageBox, msg);
                }
            }
        }

        folderInbox.close(false);
        store.close();

        return result;

    } catch (NoSuchProviderException ex) {
        logger.error("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store");
        ex.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }
    result.setSingleElement(false);
    return result;
}

From source file:org.jevis.emaildatasource.EMailManager.java

/**
 * Get list of messages// w ww .ja  v a  2  s  .  c  om
 *
 * @param folder
 * @param conn
 *
 * @return List of Message
 */
private static List<Message> getMessageList(Folder folder, EMailChannelParameters chanParam) {

    List<Message> messageList = null;

    SearchTerm term = chanParam.getSearchTerms();
    try {
        folder.open(Folder.READ_ONLY);
    } catch (MessagingException ex) {
        Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE,
                "EMail folder is not available to read.", ex);
    }
    Message[] msgs = null;

    Logger.getLogger(EMailManager.class.getName()).log(Level.INFO, "Folder is open: {0}", folder.isOpen());
    if (chanParam.getProtocol().equalsIgnoreCase(EMailConstants.Protocol.IMAP)) {
        try {
            msgs = folder.search(term);
        } catch (MessagingException ex) {
            Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE, "Unable to search messages", ex);
        }
    } else if (chanParam.getProtocol().equalsIgnoreCase(EMailConstants.Protocol.POP3)) {
        try {
            //                int[] msgnums = new int[1000];
            //                Message[] messages = folder.getMessages(msgnums);
            Message[] messages = folder.getMessages();
            messages = filterPOP3ByDate(messages, chanParam.getLastReadout());
            msgs = folder.search(term, messages);
        } catch (MessagingException ex) {
            Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE,
                    "POP3: failed to receive messages from a folder.", ex);
        }
    } else {
        Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE, "Unable to search messages");
    }

    messageList = Arrays.asList(msgs);

    Logger.getLogger(EMailManager.class.getName()).log(Level.INFO, "Messages found: {0}", messageList.size());

    return messageList;
}

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

public List<Message> getMessages() throws Throwable {
    List<Message> messageList = null;
    try {/*from  w  ww .  ja va2 s  .c o m*/
        Folder folder = this.getCurrentFolder();
        folder.open(Folder.READ_ONLY);
        CurrentFolderMessagesInfo folderInfos = (CurrentFolderMessagesInfo) this.getRequest().getSession()
                .getAttribute(CurrentFolderMessagesInfo.CURRENT_FOLDER_MESSAGES);
        //if (this.hasToReloadMessages(folder, folderInfos)) {
        Message messages[] = folder.getMessages();
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.ENVELOPE);
        folder.fetch(messages, profile);
        this.setOpenedFolder(folder);
        messageList = Arrays.asList(messages);
        this.orderMessages(messageList);
        folderInfos = new CurrentFolderMessagesInfo(this.getCurrentFolderName(), messageList);
        this.getRequest().getSession().setAttribute(CurrentFolderMessagesInfo.CURRENT_FOLDER_MESSAGES,
                folderInfos);
        //} else {
        //   messageList = folderInfos.getMessages();
        //}
    } catch (Throwable t) {
        _logger.error("Error extracting messages", t);
        throw t;
    }
    return messageList;
}