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: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 va  2s.c  om
    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;
        try {
            if (!dst.create(src.getType())) {
                System.out.println("couldn't create " + dst.getFullName());
                return;
            }
        } catch (MessagingException mex) {
            // might not be able to create a folder that holds both
            if (src.getType() != (Folder.HOLDS_MESSAGES | Folder.HOLDS_FOLDERS))
                throw mex;
            if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : 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:org.xwiki.contrib.mail.internal.AbstractMailStore.java

/**
 * @param folder//www .j a  va2s.c  o  m
 * @param message
 * @throws MessagingException
 */
public void write(String folder, Message message) throws MessagingException {
    // getLogger().info("Delivering " + message + " to " + this.location + " / " + folder);

    final Store store = getJavamailStore(true);
    store.connect();
    final Folder mailFolder = store.getDefaultFolder().getFolder(folder);
    if (!mailFolder.exists()) {
        mailFolder.create(Folder.HOLDS_MESSAGES);
    }
    mailFolder.open(Folder.READ_WRITE);
    // If message is already archived, do nothing
    final Message existingMessage = read(folder, message.getHeader("Message-ID")[0]);
    if (existingMessage == null) {
        // The Store Provider may add some headers to the message to store, but IMAPMessage are read-only
        // So we clone the message before storing it
        final MimeMessage cloned = cloneEmail(message);
        mailFolder.appendMessages(new Message[] { cloned });
    }

    mailFolder.close(true);
    store.close();
}

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

/**
 * ????/* w ww.  java 2  s .c o 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.syncope.core.notification.NotificationTest.java

private boolean verifyMail(final String sender, final String subject) throws Exception {
    LOG.info("Waiting for notification to be sent...");
    try {/*from w w w  . j  av a2  s  .  c o  m*/
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    }

    boolean found = false;
    Session session = Session.getDefaultInstance(System.getProperties());
    Store store = session.getStore("pop3");
    store.connect(pop3Host, pop3Port, 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();
    return found;
}

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

/**
 * Retrieve HTML representation of mail message
 * // www  .j ava2 s .  c  om
 * @param mid
 * @return
 */
public String getHTMLMessage(int mid) {

    String html = null;
    if (store == null)
        return html;

    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;

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

        if (m == null)
            return html;
        html = mail2HTML(m);

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

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

    }

    return html;

}

From source file:org.apache.syncope.core.logic.NotificationTest.java

private boolean verifyMail(final String sender, final String subject) throws Exception {
    LOG.info("Waiting for notification to be sent...");
    try {/*from   w ww.  j a  va  2  s.c  o  m*/
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    }

    boolean found = false;
    Session session = Session.getDefaultInstance(System.getProperties());
    Store store = session.getStore("pop3");
    store.connect(POP3_HOST, POP3_PORT, MAIL_ADDRESS, MAIL_PASSWORD);

    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();
    return found;
}

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

public void closeFolder(Folder jxFolder, boolean expunge) throws MailException {

    try {//from  ww  w  .ja  va 2 s  .  c  o m
        if ((jxFolder == null) || !jxFolder.isOpen()) {
            return;
        }

        if (expunge) {
            jxFolder.expunge();
        }

        jxFolder.close(expunge);
    } catch (MessagingException me) {
        throw new MailException(me);
    }
}

From source file:com.sonicle.webtop.mail.MailAccount.java

public boolean deleteFolder(Folder folder) throws MessagingException {
    for (Folder subfolder : folder.list()) {
        deleteFolder(subfolder);/*from  w  ww. j  a  v a 2  s. com*/
    }
    try {
        folder.close(false);
    } catch (Throwable exc) {
    }
    boolean retval = folder.delete(true);
    if (retval) {
        destroyFolderCache(folder.getFullName());
    }
    return retval;
}

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   w  ww.  j  ava 2 s  .co  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:gmailclientfx.controllers.SpamController.java

public void fetchSpam() {
    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"));

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

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