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:gmailclientfx.controllers.PoslaneController.java

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

    poslaneTable.setItems(data);/*ww w .j a v  a  2s .  c  om*/
    poslaneTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = poslaneTable.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 poslane = null;
        Folder[] folders = store.getDefaultFolder().list("*");
        for (Folder f : folders) {
            IMAPFolder imapFolder = (IMAPFolder) f;
            for (String att : imapFolder.getAttributes()) {
                if ("\\Sent".equals(att)) {
                    poslane = f;
                }
            }
        }
        poslane.open(Folder.READ_WRITE);

        MimeMessage[] seenMessages = (MimeMessage[]) poslane
                .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, "SENT");
            data.add(msg);
        }

        MimeMessage[] unseenMessages = (MimeMessage[]) poslane
                .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, "SENT");
            data.add(msg);
        }
        poslane.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(PoslaneController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:gmailclientfx.controllers.ObrisaneController.java

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

    obrisaneTable.setItems(data);/* www.ja va  2  s .c o  m*/
    obrisaneTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = obrisaneTable.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.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!");
                        }

                    });
                    stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - "
                            + PregledEmailaHelper.getMsg().getSender());
                } 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 obrisane = null;
        Folder[] folders = store.getDefaultFolder().list("*");
        for (Folder f : folders) {
            IMAPFolder imapFolder = (IMAPFolder) f;
            for (String att : imapFolder.getAttributes()) {
                if ("\\Trash".equals(att)) {
                    obrisane = f;
                }
            }
        }
        obrisane.open(Folder.READ_WRITE);

        MimeMessage[] seenMessages = (MimeMessage[]) obrisane
                .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, "DELETED");
            data.add(msg);
        }

        MimeMessage[] unseenMessages = (MimeMessage[]) obrisane
                .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, "DELETED");
            data.add(msg);
        }
        obrisane.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(ObrisaneController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:gmailclientfx.controllers.NedovrseneController.java

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

    nedovrseneTable.setItems(data);/*from  w ww . j  a  v a  2  s .c o  m*/
    nedovrseneTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = nedovrseneTable.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 nedovrsene = null;
        Folder[] folders = store.getDefaultFolder().list("*");
        for (Folder f : folders) {
            IMAPFolder imapFolder = (IMAPFolder) f;
            for (String att : imapFolder.getAttributes()) {
                if ("\\Drafts".equals(att)) {
                    nedovrsene = f;
                }
            }
        }
        nedovrsene.open(Folder.READ_WRITE);

        MimeMessage[] seenMessages = (MimeMessage[]) nedovrsene
                .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, "DRAFT");
            data.add(msg);
        }

        MimeMessage[] unseenMessages = (MimeMessage[]) nedovrsene
                .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, "DRAFT");
            data.add(msg);
        }
        nedovrsene.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(NedovrseneController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java

private Object getMessage(String requestMsgId) {
    Session session = Session.getInstance(props, null);
    session.setDebug(log.isTraceEnabled());
    Store store = null;//from   ww  w  . ja v a 2 s .com

    try {
        store = session.getStore("pop3");
        store.connect(username, password);
        Folder folder = store.getFolder(MailConstants.DEFAULT_FOLDER);
        folder.open(Folder.READ_WRITE);
        Message[] msgs = folder.getMessages();
        log.debug(msgs.length + " replies in reply mailbox");
        for (Message m : msgs) {
            String[] inReplyTo = m.getHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO);
            log.debug("Got reply to : " + Arrays.toString(inReplyTo));
            if (inReplyTo != null && inReplyTo.length > 0) {
                for (int j = 0; j < inReplyTo.length; j++) {
                    if (requestMsgId.equals(inReplyTo[j])) {
                        m.setFlag(Flags.Flag.DELETED, true);
                        return m.getContent();
                    }
                }
            }
            m.setFlag(Flags.Flag.DELETED, true);
        }
        folder.close(true);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException ignore) {
            }
            store = null;
        }
    }
    return null;
}

From source file:org.nuxeo.cm.event.MailInjectionListener.java

public void handleEvent(Event event) throws ClientException {
    MailService mailService = Framework.getService(MailService.class);
    MessageActionPipe pipe = mailService.getPipe(MAILBOX_PIPE);

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

    Folder rootFolder = null;

    try (CoreSession session = CoreInstance.openCoreSessionSystem(null)) {
        // initialize context
        ExecutionContext initialExecutionContext = new ExecutionContext();
        initialExecutionContext.put(AbstractCaseManagementMailAction.CORE_SESSION_KEY, session);
        initialExecutionContext.put(AbstractCaseManagementMailAction.MIMETYPE_SERVICE_KEY,
                Framework.getService(MimetypeRegistry.class));
        initialExecutionContext.put(AbstractCaseManagementMailAction.CASEMANAGEMENT_SERVICE_KEY,
                Framework.getService(CaseDistributionService.class));

        // open store
        Store store = mailService.getConnectedStore(IMPORT_MAILBOX);
        rootFolder = store.getFolder(INBOX);
        rootFolder.open(Folder.READ_WRITE);
        Flags flags = new Flags();
        flags.add(Flag.SEEN);// w  ww  . j  av  a  2 s . c o m
        SearchTerm term = new FlagTerm(flags, false);
        Message[] unreadMessages = rootFolder.search(term);

        // perform import
        visitor.visit(unreadMessages, initialExecutionContext);

        // save session
        session.save();

        if (rootFolder.isOpen()) {
            try {
                rootFolder.close(true);
            } catch (MessagingException e) {
                log.error(e.getMessage(), e);
            }
        }
    } catch (MessagingException e) {
        log.error(e, e);
    }
}

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

public void getMessage(cfImapConnection imapConnection, String rootFolder, long messageID, String _attachURI,
        String _attachDIR) throws cfmRunTimeException {
    try {/*from w ww. j  a  v  a2s .c o  m*/
        Folder folderToList;

        if (rootFolder == null || rootFolder.length() == 0)
            folderToList = imapConnection.mailStore.getDefaultFolder();
        else
            folderToList = imapConnection.mailStore.getFolder(rootFolder);

        if ((folderToList.getType() & Folder.HOLDS_MESSAGES) != 0) {

            if (!folderToList.isOpen())
                folderToList.open(Folder.READ_ONLY);

            boolean bResult = false;
            if (folderToList instanceof UIDFolder)
                bResult = extractMessage(((UIDFolder) folderToList).getMessageByUID(messageID), messageID,
                        _attachURI, _attachDIR);
            else
                bResult = extractMessage(folderToList.getMessage((int) messageID), messageID, _attachURI,
                        _attachDIR);

            if (!bResult)
                imapConnection.setStatus(false, "Message does not exist");
            else
                imapConnection.setStatus(true, "");

            folderToList.close(false);
        }

    } catch (Exception E) {
        imapConnection.setStatus(false, E.getMessage());
    }
}

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

/**
 * /* w  w w .j  a  va2  s.c o  m*/
 */
@Override
public List<IMessage> receive(boolean clear) {
    List<IMessage> result = new ArrayList<IMessage>();

    try {
        String user = properties.getProperty("pop3.login.user");
        String password = properties.getProperty("pop3.login.password");

        String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        Properties pop3Props = new Properties();

        pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
        pop3Props.setProperty("mail.pop3.port", properties.getProperty("pop3.port"));
        pop3Props.setProperty("mail.pop3.socketFactory.port", properties.getProperty("pop3.port"));

        URLName url = new URLName("pop3", properties.getProperty("pop3.host"),
                Integer.valueOf(properties.getProperty("pop3.port")), "", user, password);

        Session session = Session.getInstance(pop3Props, null);
        Store store = new POP3SSLStore(session, url);
        store.connect();

        // Open the Folder
        Folder folder = store.getDefaultFolder();
        folder = folder.getFolder("INBOX");

        if (folder == null) {
            throw new RuntimeException("Invalid folder INBOX");
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }

        int count = folder.getMessageCount();
        // Message numbers start at 1
        for (int i = 1; i <= count; i++) {
            // Get a message by its sequence number
            Message m = folder.getMessage(i);
            Address[] from = m.getFrom();
            String type = from[0].getType();

            IMessage message = new MailMessage(from[0].toString(), this, m.getSubject(), getContent(m));

            result.add(message);

            // delete message ?
            if (clear)
                m.setFlag(Flags.Flag.DELETED, true);
        }

        // "true" actually deletes flagged messages from folder
        folder.close(clear);
        store.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.apache.juddi.v3.tck.UDDI_090_Smtp_ExternalTest.java

/**
 * gets all current messages from the mail server and returns the number
 * of messages containing the string, messages containing the string are
 * deleted from the mail server String is the body of each message
 *
 * @return number of matching and deleted messages
 * @param contains a string to search for
 *///from  www. j a v a 2  s  .  c om
private static int fetchMail(String contains) {

    //final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    /* Set the mail properties */
    Properties properties = TckPublisher.getProperties();
    // Set manual Properties

    int found = 0;
    Session session = Session.getDefaultInstance(properties, null);
    Store store = null;
    try {
        store = session.getStore("pop3");

        store.connect(properties.getProperty("mail.pop3.host"),
                Integer.parseInt(properties.getProperty("mail.pop3.port", "110")),
                properties.getProperty("mail.pop3.username"), properties.getProperty("mail.pop3.password"));
        /* Mention the folder name which you want to read. */
        // inbox = store.getDefaultFolder();
        // inbox = inbox.getFolder("INBOX");
        Folder inbox = store.getFolder("INBOX");

        /* Open the inbox using store. */
        inbox.open(Folder.READ_WRITE);

        Message messages[] = inbox.getMessages();

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

            MimeMessageParser p = new MimeMessageParser(new MimeMessage(session, messages[i].getInputStream()));
            Enumeration allHeaders = p.getMimeMessage().getAllHeaders();
            while (allHeaders.hasMoreElements()) {
                Object j = allHeaders.nextElement();
                if (j instanceof javax.mail.Header) {
                    javax.mail.Header msg = (javax.mail.Header) j;
                    logger.info("XML as message header is " + msg.getValue());
                    if (msg.getValue().contains(contains)) {
                        //found it
                        messages[i].setFlag(Flags.Flag.DELETED, true);
                        found++;
                    }
                }
            }
            for (int k = 0; k < p.getAttachmentList().size(); k++) {
                InputStream is = p.getAttachmentList().get((k)).getInputStream();
                QuotedPrintableCodec qp = new QuotedPrintableCodec();
                // If "is" is not already buffered, wrap a BufferedInputStream
                // around it.
                if (!(is instanceof BufferedInputStream)) {
                    is = new BufferedInputStream(is);
                }
                int c;
                StringBuilder sb = new StringBuilder();
                System.out.println("Message : ");
                while ((c = is.read()) != -1) {
                    sb.append(c);
                    System.out.write(c);
                }
                is.close();
                String decoded = qp.decode(sb.toString());
                logger.info("decode message is " + decoded);
                if (decoded.contains(contains)) {
                    //found it
                    messages[i].setFlag(Flags.Flag.DELETED, true);
                    found++;
                }
            }

        }
        inbox.close(true);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (Exception ex) {
            }
        }
    }
    return found;
}

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

@Test
public void testOpenImapConnection() {
    URL url = this.getClass().getClassLoader().getResource("truststore.jks");
    String path = url.getPath();/*from   w  ww . ja va 2  s.c  o  m*/
    System.setProperty("javax.net.ssl.trustStore", path);
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    Store mailAccount = null;
    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 --
        Message[] msgs = inbox.getMessages();
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.FLAGS);
        inbox.fetch(msgs, profile);
    } catch (MessagingException mex) {
        SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", mex);
    } catch (Exception mex) {
        SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", mex);
    } finally {
        // -- Close down nicely --
        try {
            if (inbox != null) {
                inbox.close(false);
            }
            if (mailAccount != null) {
                mailAccount.close();
            }
        } catch (Exception ex2) {
            SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", ex2);
        }
    }

}

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

/**
 * Retrieve attachment from message id/* w  w w  .j a v  a 2s .  c  o  m*/
 * 
 * @param mid
 * @return
 */
public FileUtil getAttachment(int mid) {

    FileUtil file = null;
    if (store == null)
        return file;

    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();
        Message m = null;

        /* 
         * Message message = folder.getMessage(mid); 
         * 
         * the method 'getMessage' always returns an
         * index out of bound error, so we have to
         * introduce the hack below
         */

        for (int i = 0; i < messages.length; i++) {
            if (i == mid)
                m = messages[i];
        }

        if (m == null)
            return file;

        Object content = m.getContent();
        if (content instanceof Multipart) {
            file = handleMultipart((Multipart) content, true);

        } else {
            file = handlePart(m, true);

        }

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

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

    }

    return file;

}