Example usage for javax.mail Folder close

List of usage examples for javax.mail Folder close

Introduction

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

Prototype

public abstract void close(boolean expunge) throws MessagingException;

Source Link

Document

Close this Folder.

Usage

From source file:org.apache.axis2.transport.mail.MailRequestResponseClient.java

private Message getMessage(String requestMsgId) throws Exception {
    MimeMessage response = null;//from ww  w .  ja  v  a  2 s .  c om
    Folder folder = store.getFolder(MailConstants.DEFAULT_FOLDER);
    folder.open(Folder.READ_WRITE);
    Message[] msgs = folder.getMessages();
    log.debug(msgs.length + " messages in mailbox");
    loop: for (Message m : msgs) {
        MimeMessage mimeMessage = (MimeMessage) m;
        String[] inReplyTo = mimeMessage.getHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO);
        log.debug("Found message " + mimeMessage.getMessageID() + " in reply to " + Arrays.toString(inReplyTo));
        if (inReplyTo != null && inReplyTo.length > 0) {
            for (int j = 0; j < inReplyTo.length; j++) {
                if (requestMsgId.equals(inReplyTo[j])) {
                    log.debug("Identified message " + mimeMessage.getMessageID() + " as the response to "
                            + requestMsgId + "; retrieving it from the store");
                    // We need to create a copy so that we can delete the original and close the folder
                    response = new MimeMessage(mimeMessage);
                    log.debug("Flagging message " + mimeMessage.getMessageID() + " for deletion");
                    mimeMessage.setFlag(Flags.Flag.DELETED, true);
                    break loop;
                }
            }
        }
        log.warn("Don't know what to do with message " + mimeMessage.getMessageID() + "; skipping");
    }
    folder.close(true);
    return response;
}

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  w w.  j a  v a  2s .  co 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:EmailBean.java

private void handleMessages(HttpServletRequest request, PrintWriter out) throws IOException, ServletException {

    HttpSession httpSession = request.getSession();
    String user = (String) httpSession.getAttribute("user");
    String password = (String) httpSession.getAttribute("pass");
    String popAddr = (String) httpSession.getAttribute("pop");

    Store popStore = null;// w w w . ja  v  a 2  s  .  c  o m
    Folder folder = null;

    if (!check(popAddr))
        popAddr = EmailBean.DEFAULT_SERVER;

    try {

        if ((!check(user)) || (!check(password)))
            throw new ServletException("A valid username and password is required to check email.");

        Properties properties = System.getProperties();

        Session session = Session.getDefaultInstance(properties);

        popStore = session.getStore("pop3");

        popStore.connect(popAddr, user, password);

        folder = popStore.getFolder("INBOX");

        if (!folder.exists())
            throw new ServletException("An 'INBOX' folder does not exist for the user.");

        folder.open(Folder.READ_ONLY);

        Message[] messages = folder.getMessages();
        int msgLen = messages.length;

        if (msgLen == 0)
            out.println("<h2>The INBOX folder does not yet contain any email messages.</h2>");

        for (int i = 0; i < msgLen; i++) {
            displayMessage(messages[i], out);
            out.println("<br /><br />");
        }

    } catch (Exception exc) {

        out.println("<h2>Sorry, an error occurred while accessing the email messages.</h2>");
        out.println(exc.toString());

    } finally {
        try {
            if (folder != null)
                folder.close(false);

            if (popStore != null)
                popStore.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.gcaldaemon.core.GmailEntry.java

public final GmailMessage[] receive(String title) throws Exception {

    // Open 'INBOX' folder
    Folder inbox = mailbox.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);/*from   w ww .  j  ava  2 s. co  m*/
    Message[] messages = inbox.getMessages();
    if (messages == null || messages.length == 0) {
        return new GmailMessage[0];
    }

    // Loop on messages
    LinkedList list = new LinkedList();
    for (int i = 0; i < messages.length; i++) {
        Message msg = messages[i];
        if (!msg.isSet(Flag.SEEN)) {
            String subject = msg.getSubject();
            if (title == null || title.length() == 0 || title.equals(subject)) {
                GmailMessage gm = new GmailMessage();
                Address[] from = msg.getFrom();
                msg.setFlag(Flag.SEEN, true);
                if (from == null || from.length == 0) {
                    continue;
                }
                gm.subject = subject;
                gm.from = from[0].toString();
                gm.memo = String.valueOf(msg.getContent());
                list.addLast(gm);
            }
        }
    }
    inbox.close(true);

    // Return the array of the messages
    GmailMessage[] array = new GmailMessage[list.size()];
    list.toArray(array);
    return array;
}

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

@Override
public boolean deleteMessages(MailStoreConfiguration config, String[] uuids) {
    Authenticator auth = credentialsProvider.getAuthenticator();
    Folder inbox = null;
    try {//from ww  w. j av  a  2s  .  com

        // Retrieve user's inbox
        Session session = openMailSession(config, auth);
        inbox = getUserInbox(session, config.getInboxFolderName());

        // Verify that we can even perform this operation
        if (!(inbox instanceof UIDFolder)) {
            String msg = "Delete feature is supported only for UIDFolder instances";
            throw new UnsupportedOperationException(msg);
        }

        inbox.open(Folder.READ_WRITE);

        Message[] msgs = ((UIDFolder) inbox).getMessagesByUID(getMessageUidsAsLong(uuids));
        inbox.setFlags(msgs, new Flags(Flag.DELETED), true);

        return true; // Indicate success

    } catch (MessagingException e) {
        log.error("Messaging exception while deleting messages", e);
    } finally {
        if (inbox != null) {
            try {
                inbox.close(false);
            } catch (Exception e) {
                log.warn("Can't close correctly javamail inbox connection");
            }
            try {
                inbox.getStore().close();
            } catch (Exception e) {
                log.warn("Can't close correctly javamail store connection");
            }
        }
    }

    return false; // We failed if we reached this point
}

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

@Override
public boolean setMessageReadStatus(MailStoreConfiguration config, String[] uuids, boolean read) {
    Authenticator auth = credentialsProvider.getAuthenticator();
    Folder inbox = null;
    try {//from  w w  w  .j a  va 2s.c  om
        // Retrieve user's inbox
        Session session = openMailSession(config, auth);
        inbox = getUserInbox(session, config.getInboxFolderName());

        // Verify that we can even perform this operation log info if it isn't capable of operation
        if (!(inbox instanceof UIDFolder)) {
            String msg = "Toggle unread feature is supported only for UIDFolder instances";
            log.info(msg);
            return false;
        }

        inbox.open(Folder.READ_WRITE);

        Message[] msgs = ((UIDFolder) inbox).getMessagesByUID(getMessageUidsAsLong(uuids));
        inbox.setFlags(msgs, new Flags(Flag.SEEN), read);

        return true; // Indicate success

    } catch (MessagingException e) {
        log.error("Messaging exception while deleting messages", e);
    } finally {
        if (inbox != null) {
            try {
                inbox.close(false);
            } catch (Exception e) {
                log.warn("Can't close correctly javamail inbox connection");
            }
            try {
                inbox.getStore().close();
            } catch (Exception e) {
                log.warn("Can't close correctly javamail store connection");
            }
        }
    }

    return false; // We failed if we reached this point
}

From source file:org.pentaho.di.job.entries.getpop.MailConnection.java

/**
 * Check if a folder exists on server (only IMAP).
 *
 * @param foldername//  w  w  w  .  j  a v a2  s. co  m
 *          the name of the folder
 * @return true is folder exists
 */
public boolean folderExists(String foldername) {
    boolean retval = false;
    Folder dfolder = null;
    try {
        // Open destination folder
        dfolder = getRecursiveFolder(foldername);
        if (dfolder.exists()) {
            retval = true;
        }
    } catch (Exception e) {
        // Ignore errors
    } finally {
        try {
            if (dfolder != null) {
                dfolder.close(false);
            }
        } catch (Exception e) { /* Ignore */
        }
    }
    return retval;
}

From source file:org.pentaho.di.job.entries.getpop.MailConnection.java

/**
 * Returns all subfolders of the folder folder
 *
 * @param folder/*  w w w . j  av a  2s  .c om*/
 *          target folder
 * @return sub folders
 */
public String[] returnAllFolders(String folder) throws KettleException {

    Folder dfolder = null;
    String[] retval = null;
    try {
        if (Utils.isEmpty(folder)) {
            // Default folder
            dfolder = getStore().getDefaultFolder();
        } else {
            dfolder = getStore().getFolder(folder);
        }
        retval = returnAllFolders(dfolder);
    } catch (Exception e) {
        // Ignore errors
    } finally {
        try {
            if (dfolder != null) {
                dfolder.close(false);
            }
        } catch (Exception e) { /* Ignore */
        }
    }
    return retval;
}

From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * Retrieve mail messages in a JSON representation
 * /*from w  w  w  . j a v  a  2  s.  c o  m*/
 * @return
 */
public JSONArray getJMessages() {

    JSONArray jMessages = new JSONArray();
    if (store == null)
        return jMessages;

    try {
        /*
         * Connect to IMAP store
         */
        store.connect();

        /*
         * Retrieve & open INBOX folder
         */
        Folder folder = store.getFolder(ImapConstants.INBOX);
        folder.open(Folder.READ_ONLY);

        Message[] messages = folder.getMessages();
        for (int i = 0; i < messages.length; i++) {

            Message m = messages[i];

            JSONObject jMessage = new JSONObject();

            jMessage.put(ImapConstants.J_KEY, ""); // introduced to be compatible with posted emails             
            jMessage.put(ImapConstants.J_ID, i); // message identifier to retrieve from external server

            jMessage.put(ImapConstants.J_SUBJECT, m.getSubject());
            jMessage.put(ImapConstants.J_DATE, m.getSentDate());

            String from = "";

            Address[] addresses = m.getFrom();
            for (Address address : addresses) {

                InternetAddress internetAddress = (InternetAddress) address;
                from = internetAddress.getPersonal();

            }

            jMessage.put(ImapConstants.J_FROM, from);

            FileUtil attachment = getAttachment(m);
            if (attachment == null) {
                jMessage.put(ImapConstants.J_ATTACHMENT, false);

            } else {
                jMessage.put(ImapConstants.J_ATTACHMENT, true);

            }

            jMessages.put(jMessages.length(), jMessage);

        }

        folder.close(false);
        store.close();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
    }

    return jMessages;
}

From source file:com.silverpeas.mailinglist.service.job.TestYahooMailConnection.java

@Test
public void testOpenImapConnection() throws Exception {
    Store mailAccount = null;// w  ww  .  jav a2 s.  c  om
    Folder inbox = null;
    Session mailSession = Session.getInstance(System.getProperties());
    try {
        mailSession.setDebug(true);
        mailAccount = mailSession.getStore(props.getProperty("mail.server.protocol"));
        mailAccount.connect(props.getProperty("mail.server.host"),
                Integer.parseInt(props.getProperty("mail.server.port")), props.getProperty("mail.server.login"),
                props.getProperty("mail.server.password"));
        inbox = mailAccount.getFolder("INBOX");
        if (inbox == null) {
            throw new MessagingException("No POP3 INBOX");
        }
        // -- Open the folder for read write --
        inbox.open(Folder.READ_WRITE);

        // -- Get the message wrappers and process them --
        javax.mail.Message[] msgs = inbox.getMessages();
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.FLAGS);
        inbox.fetch(msgs, profile);
        MailProcessor processor = new MailProcessor();
        MessageListener mailingList = mock(MessageListener.class);
        when(mailingList.checkSender(anyString())).thenReturn(Boolean.TRUE);
        when(mailingList.getComponentId()).thenReturn("mailingList38");
        MessageEvent event = new MessageEvent();
        for (javax.mail.Message message : msgs) {
            processor.prepareMessage((MimeMessage) message, mailingList, event);
        }
        assertThat(event.getMessages(), is(notNullValue()));
        assertThat(event.getMessages().size(), is(msgs.length));
        for (com.silverpeas.mailinglist.service.model.beans.Message message : event.getMessages()) {
            assertThat(message, is(notNullValue()));
            assertThat(message.getMessageId(), is(notNullValue()));
        }
    } finally {
        // -- Close down nicely --
        if (inbox != null) {
            inbox.close(false);
        }
        if (mailAccount != null) {
            mailAccount.close();
        }
    }
}