Example usage for javax.mail Folder open

List of usage examples for javax.mail Folder open

Introduction

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

Prototype

public abstract void open(int mode) throws MessagingException;

Source Link

Document

Open this Folder.

Usage

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

/**
 * ????/*from ww  w .  ja v  a 2  s. 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.apache.usergrid.rest.management.RegistrationIT.java

private Message[] getMessages(String host, String user, String password)
        throws MessagingException, IOException {

    Session session = Session.getDefaultInstance(new Properties());
    Store store = session.getStore("imap");
    store.connect(host, user, password);

    Folder folder = store.getFolder("inbox");
    folder.open(Folder.READ_ONLY);
    Message[] msgs = folder.getMessages();

    for (Message m : msgs) {
        logger.info("Subject: " + m.getSubject());
        logger.info("Body content 0 " + ((MimeMultipart) m.getContent()).getBodyPart(0).getContent());
        logger.info("Body content 1 " + ((MimeMultipart) m.getContent()).getBodyPart(1).getContent());
    }/*from   w ww  .  j  av a2s. c o m*/
    return msgs;
}

From source file:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java

private void readMessagesFolder(Folder folder) throws MessagingException, IOException, SearchLibException {
    folder.open(Folder.READ_ONLY);
    String folderFullName = folder.getFullName();
    try {/*from   w  w  w.  j  a va 2s.  com*/
        int max = folder.getMessageCount();
        int i = 0;
        final int buffer = item.getBufferSize();
        while (i < max && !thread.isAborted()) {
            thread.setStatusInfo(CrawlStatus.CRAWL);
            int end = i + buffer;
            if (end > max)
                end = max;
            Message[] messages = folder.getMessages(i + 1, end);
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            folder.fetch(messages, fp);
            for (Message message : messages) {
                if (thread.isAborted())
                    break;
                i++;
                String messageId = getMessageId(folder, message);
                if (StringUtils.isEmpty(messageId))
                    continue;
                if (thread.isAlreadyIndexed(messageId)) {
                    thread.incIgnored();
                    continue;
                }
                IndexDocument crawlIndexDocument = new IndexDocument(item.getLang());
                IndexDocument parserIndexDocument = new IndexDocument(item.getLang());
                crawlIndexDocument.addString(MailboxFieldEnum.folder.name(), folderFullName);
                try {
                    readMessage(crawlIndexDocument, parserIndexDocument, folder, message, messageId);
                    thread.addDocument(crawlIndexDocument, parserIndexDocument);
                } catch (Exception e) {
                    Logging.warn(e);
                    thread.incError();
                }
            }
        }
    } finally {
        folder.close(false);
    }
}

From source file:server.MailPop3Expert.java

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

    while (store.isConnected()) {
        try {//  ww w . jav  a  2 s.  c o  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:populate.java

private static void copy(Folder src, Folder dst) throws MessagingException {
    System.out.println("Populating " + dst.getFullName());

    Folder ddst = dst;//from  w ww  .j  a v a 2 s.  c o m
    Folder[] srcFolders = null;
    if ((src.getType() & Folder.HOLDS_FOLDERS) != 0)
        srcFolders = src.list();
    boolean srcHasChildren = srcFolders != null && srcFolders.length > 0;

    if (!dst.exists()) {
        // Create it.
        boolean dstHoldsOnlyFolders = false;
        if (!dst.create(src.getType())) {
            // might not be able to create a folder that holds both
            if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : Folder.HOLDS_MESSAGES)) {
                // might only be able to create one type (Gmail)
                if (!dst.create(Folder.HOLDS_MESSAGES)) {
                    System.out.println("couldn't create " + dst.getFullName());
                    return;
                }
            }
            dstHoldsOnlyFolders = srcHasChildren;
        }

        // Copy over any messges from src to dst
        if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            if (dstHoldsOnlyFolders) {
                if (src.getMessageCount() > 0) {
                    System.out.println("Unable to copy messages from " + src.getFullName() + " to "
                            + dst.getFullName() + " because destination holds only folders");
                }
            } else
                copyMessages(src, dst);
            src.close(false);
        }
    } else {
        System.out.println(dst.getFullName() + " already exists");
        // Copy over any messges from src to dst
        if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            copyMessages(src, dst);
            src.close(false);
        }
    }

    // Copy over subfolders
    if (srcHasChildren) {
        for (int i = 0; i < srcFolders.length; i++) {
            // skip special directories?
            if (skipSpecial) {
                if (srcFolders[i].getName().equals("SCCS") || srcFolders[i].getName().equals("Drafts")
                        || srcFolders[i].getName().equals("Trash")
                        || srcFolders[i].getName().equals("Shared Folders"))
                    continue;
            }
            copy(srcFolders[i], dst.getFolder(srcFolders[i].getName()));
        }
    }
}

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

/**
 * Returns new messages and fetches details for each message.
 *///from w w  w  .j  a v  a  2 s .com
@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:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java

public void generateMailNotification(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword, String notificationType, String fromFilter, String subjectFilter)
        throws Exception {
    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);// w ww.  j  a va2  s.co  m
    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_WRITE);

        // check if fromFilter is specified
        List<String> fromFilterList = null;

        if (StringUtils.isNotBlank(fromFilter)) {
            String[] fromFilterArray = StringUtils.split(fromFilter, "|");
            fromFilterList = Arrays.asList(fromFilterArray);
        }

        // check if subjectFilter is specified
        List<String> subjectFilterList = null;
        if (StringUtils.isNotBlank(subjectFilter)) {
            String[] subjectFilterArray = StringUtils.split(subjectFilter, "|");
            subjectFilterList = Arrays.asList(subjectFilterArray);
        }
        Map<String, Object> context = new HashMap<String, Object>();
        // 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 address = fromAddress[0].toString();
            String from = extractFromAddress(address);
            if (StringUtils.isBlank(from)) {
                logger.warn("From Address is not proper " + from);
                return;
            }
            boolean isValidFrom = isValidMatch(fromFilterList, from);

            // filter based on fromFilter specified
            if (null == fromFilterList || isValidFrom) {
                String subject = msg.getSubject();

                boolean isValidSubject = isValidMatch(subjectFilterList, subject);
                if (null == subjectFilterList || isValidSubject) {
                    String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
                    String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
                    String sentDate = msg.getSentDate().toString();

                    String messageContent = "";
                    try {
                        Object content = msg.getContent();
                        if (content != null) {
                            messageContent = content.toString();
                        }
                    } catch (Exception ex) {
                        messageContent = "[Error downloading content]";
                        ex.printStackTrace();
                    }
                    context.put("from", from);
                    context.put("to", toList);
                    context.put("cc", ccList);
                    context.put("subject", subject);
                    context.put("messagebody", messageContent);
                    context.put("sentdate", sentDate);

                    notificationController.createNotification(notificationType, context);
                    msg.setFlag(Flag.DELETED, true);
                } else {
                    logger.warn("subjectFilter doesn't match");
                }
            } else {
                logger.warn("this email originated from " + address
                        + " , which does not match fromAddress specified in the rule, it should be "
                        + fromFilter.toString());
            }
        }
        // disconnect and delete messages marked as DELETED
        folderInbox.close(true);
        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:com.seleniumtests.connectors.mails.ImapClient.java

/**
 * get list of all emails in folder//from w w  w. j a  va2s.c o  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:com.robin.utilities.Utilities.java

/**
 * A utility that waits for a gmail mailbox to receive a new message with
 * according to a given SearchTerm. Only "Not seen" messages are searched,
 * and all match is set as SEEN, but just the first occurrence of the
 * matching message is returned.//from  w  ww  .j a  v  a  2  s  . c  o  m
 * @param username the mailbox owner's user name (no @gmail.com required).
 * @param pass the user password protecting this mailbox
 * @param st the SearchTerm built to filter messages
 * @param timeoutMessage the message to show when no such mail found within
 *            timeout
 * @param timeout The maximum amount of time to wait in milliseconds.
 * @return a last from the new messages thats match the st conditions
 */
public EMail waitForMailWithSearchTerm(final String username, final String pass, final SearchTerm st,
        final String timeoutMessage, final long timeout) {
    String host = "imap.gmail.com";
    final long retryTime = 1000;

    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    props.put("mail.imaps.ssl.trust", "*");
    EMail email = null;
    Session session = Session.getDefaultInstance(props, null);
    try {
        Store store = session.getStore("imaps");
        store.connect(host, username, pass);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);
        FluentWait<Folder> waitForMail = new FluentWait<Folder>(inbox)
                .withTimeout(timeout, TimeUnit.MILLISECONDS).pollingEvery(retryTime, TimeUnit.MILLISECONDS)
                .withMessage(timeoutMessage);
        email = waitForMail.until(new Function<Folder, EMail>() {
            @Override
            public EMail apply(final Folder inbox) {
                EMail email = null;
                FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
                SearchTerm sst = new AndTerm(ft, st);
                try {
                    inbox.getMessageCount();
                    Message[] messages = inbox.search(sst);
                    for (Message message : messages) {
                        message.setFlag(Flag.SEEN, true);
                    }
                    if (messages.length > 0) {
                        return new EMail(messages[0]);
                    }
                } catch (MessagingException e) {
                    Assert.fail(e.getMessage());
                }
                return email;
            }
        });
        inbox.close(false);
        store.close();
    } catch (MessagingException e) {
        Assert.fail(e.getMessage());
    }
    return email;
}

From source file:com.ikon.util.MailUtils.java

/**
 * Test IMAP connection//www  . ja  v  a2 s. com
 */
public static void testConnection(MailAccount ma) throws IOException {
    log.debug("testConnection({})", ma);
    Session session = Session.getDefaultInstance(getProperties());
    Store store = null;
    Folder folder = null;

    try {
        store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());
        folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        folder.close(false);
    } catch (NoSuchProviderException e) {
        throw new IOException(e.getMessage());
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    } finally {
        // Try to close folder
        if (folder != null && folder.isOpen()) {
            try {
                folder.close(false);
            } catch (MessagingException e) {
                throw new IOException(e.getMessage());
            }
        }

        // Try to close store
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                throw new IOException(e.getMessage());
            }
        }
    }

    log.debug("testConnection: void");
}