Example usage for javax.mail Folder getMessageCount

List of usage examples for javax.mail Folder getMessageCount

Introduction

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

Prototype

public abstract int getMessageCount() throws MessagingException;

Source Link

Document

Get total number of messages in this Folder.

Usage

From source file:folderlist.java

static void dumpFolder(Folder folder, boolean recurse, String tab) throws Exception {
    System.out.println(tab + "Name:      " + folder.getName());
    System.out.println(tab + "Full Name: " + folder.getFullName());
    System.out.println(tab + "URL:       " + folder.getURLName());

    if (verbose) {
        if (!folder.isSubscribed())
            System.out.println(tab + "Not Subscribed");

        if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
            if (folder.hasNewMessages())
                System.out.println(tab + "Has New Messages");
            System.out.println(tab + "Total Messages:  " + folder.getMessageCount());
            System.out.println(tab + "New Messages:    " + folder.getNewMessageCount());
            System.out.println(tab + "Unread Messages: " + folder.getUnreadMessageCount());
        }//w w  w  .  j a v a 2 s. c  o  m
        if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0)
            System.out.println(tab + "Is Directory");

        /*
         * Demonstrate use of IMAP folder attributes
         * returned by the IMAP LIST response.
         */
        if (folder instanceof IMAPFolder) {
            IMAPFolder f = (IMAPFolder) folder;
            String[] attrs = f.getAttributes();
            if (attrs != null && attrs.length > 0) {
                System.out.println(tab + "IMAP Attributes:");
                for (int i = 0; i < attrs.length; i++)
                    System.out.println(tab + "    " + attrs[i]);
            }
        }
    }

    System.out.println();

    if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
        if (recurse) {
            Folder[] f = folder.list();
            for (int i = 0; i < f.length; i++)
                dumpFolder(f[i], recurse, tab + "    ");
        }
    }
}

From source file:MainClass.java

static void dumpFolder(Folder folder, boolean recurse, String tab) throws Exception {
    System.out.println(tab + "Name:      " + folder.getName());
    System.out.println(tab + "Full Name: " + folder.getFullName());
    System.out.println(tab + "URL:       " + folder.getURLName());

    if (verbose) {
        if (!folder.isSubscribed())
            System.out.println(tab + "Not Subscribed");

        if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
            if (folder.hasNewMessages())
                System.out.println(tab + "Has New Messages");
            System.out.println(tab + "Total Messages:  " + folder.getMessageCount());
            System.out.println(tab + "New Messages:    " + folder.getNewMessageCount());
            System.out.println(tab + "Unread Messages: " + folder.getUnreadMessageCount());
        }/*  w  w  w . j a va  2s  .  co m*/
        if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0)
            System.out.println(tab + "Is Directory");

        /*
         * Demonstrate use of IMAP folder attributes returned by the IMAP LIST
         * response.
         */
        if (folder instanceof IMAPFolder) {
            IMAPFolder f = (IMAPFolder) folder;
            String[] attrs = f.getAttributes();
            if (attrs != null && attrs.length > 0) {
                System.out.println(tab + "IMAP Attributes:");
                for (int i = 0; i < attrs.length; i++)
                    System.out.println(tab + "    " + attrs[i]);
            }
        }
    }

    System.out.println();

    if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
        if (recurse) {
            Folder[] f = folder.list();
            for (int i = 0; i < f.length; i++)
                dumpFolder(f[i], recurse, tab + "    ");
        }
    }
}

From source file:org.alfresco.repo.imap.RemoteLoadTester.java

public void testListSequence() {
    System.out.println(String.format("Connecting to remote server '%s'", REMOTE_HOST));
    Properties props = System.getProperties();
    props.setProperty("mail.imap.partialfetch", "false");
    Session session = Session.getDefaultInstance(props, null);

    Store store = null;//from  w w w  . j  a va  2s .  c  o  m
    long startTime = 0;
    long endTime = 0;
    try {
        store = session.getStore("imap");
        store.connect(REMOTE_HOST, ADMIN_USER_NAME, ADMIN_USER_NAME);
        Folder[] folders = null;

        startTime = System.currentTimeMillis();
        folders = store.getDefaultFolder().list("");
        endTime = System.currentTimeMillis();
        System.out.println(String.format("LIST '', folders.length = %d, execTime = %d sec", folders.length,
                (endTime - startTime) / 1000));

        startTime = System.currentTimeMillis();
        folders = store.getDefaultFolder().list("*");
        endTime = System.currentTimeMillis();
        System.out.println(String.format("LIST *, folders.length = %d, execTime = %d sec", folders.length,
                (endTime - startTime) / 1000));

        startTime = System.currentTimeMillis();
        folders = store.getDefaultFolder().listSubscribed("*");
        endTime = System.currentTimeMillis();
        System.out.println(String.format("LSUB *, folders.length = %d, execTime = %d sec", folders.length,
                (endTime - startTime) / 1000));

        startTime = System.currentTimeMillis();
        for (Folder folder : folders) {
            folder.getMessageCount();
            //Folder f = store.getFolder(folder.getFullName());
        }
        endTime = System.currentTimeMillis();
        System.out.println(String.format("Folders Loop, folders.length = %d, execTime = %d sec", folders.length,
                (endTime - startTime) / 1000));

    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    } finally {
        try {
            store.close();
        } catch (MessagingException e) {
            System.err.println(e.getMessage());
        }
    }
}

From source file:com.ieprofile.helper.gmail.OAuth2Authenticator.java

/**
 * Connects and authenticates to an IMAP server with OAuth2. You must have
 * called {@code initialize}.//  w w  w  .  j  a v  a  2  s. c  o m
 *
 * @param host Hostname of the imap server, for example {@code
 *     imap.googlemail.com}.
 * @param port Port of the imap server, for example 993.
 * @param userEmail Email address of the user to authenticate, for example
 *     {@code oauth@gmail.com}.
 * @param oauthToken The user's OAuth token.
 * @param debug Whether to enable debug logging on the IMAP connection.
 *
 * @return An authenticated IMAPStore that can be used for IMAP operations.
 */
public List<MessageBean> connectToImap(String host, int port, String userEmail, String oauthToken,
        boolean debug) throws Exception {
    Properties props = new Properties();
    props.put("mail.imaps.sasl.enable", "true");
    props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
    props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
    Session session = Session.getInstance(props);
    session.setDebug(debug);

    final URLName unusedUrlName = null;
    IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
    final String emptyPassword = "";
    store.connect(host, port, userEmail, emptyPassword);
    Folder inbox = store.getFolder("Inbox");
    inbox.open(Folder.READ_WRITE);
    Message messages[] = inbox.getMessages();
    int messageCount = inbox.getMessageCount();
    List<String> attachments = new ArrayList<String>();
    LinkedList<MessageBean> listMessages = emailListener.sendMessage(messages, attachments);
    emailRepo.addAllMessages(listMessages);

    emailListener.folder = inbox;
    emailListener.started = false;
    emailListener.start();

    //ArrayList<String> attachments = new ArrayList<String>();
    //LinkedList<MessageBean> listMessages = getPart(messages, attachments);

    //store.close();
    return emailRepo.getMessages();
}

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  a  v a2 s  . c  o  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:edu.stanford.muse.email.MboxEmailStore.java

@Override
/** we need the Store s parameter from superclass, but it is not used in the folder store
 *//*from  www  . j  av  a2  s . c o m*/
public Pair<Folder, Integer> openFolder(Store s, String fname) throws MessagingException {
    Folder folder = openFolderWithoutCount(s, fname);
    int count = 0;
    if (folder != null)
        count = folder.getMessageCount(); // warning, do not close, we need to return an open folder

    return new Pair<>(folder, count);
}

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

/**
 * Returns the number of messages on the server
 * /* w w  w .  j  a  va  2s. c o m*/
 * @param folderName
 * @return 
 * @throws MessagingException
 */
private Integer getMessageNumber(String folderName) throws MessagingException {
    // Get folder
    Folder folder = store.getFolder(folderName);
    folder.open(Folder.READ_ONLY);

    Integer messageCount = folder.getMessageCount();

    folder.close(false);

    return messageCount;
}

From source file:edu.stanford.muse.email.ImapPopEmailStore.java

public void computeFoldersAndCounts(String cacheDir /*unused */) throws MessagingException {
    if (store == null)
        connect();/*from  w w  w .  java  2s  .co  m*/
    if (!store.isConnected())
        connect();

    doneReadingFolderCounts = false;
    this.folderInfos = new ArrayList<FolderInfo>();
    if ("pop3".equals(connectOptions.protocol) || "pop3s".equals(connectOptions.protocol)) {
        Folder f = store.getDefaultFolder();
        f = f.getFolder("INBOX");
        f.open(Folder.READ_ONLY);
        int count = f.getMessageCount();
        f.close(false);
        this.folderInfos.add(new FolderInfo(getAccountID(), "INBOX", "INBOX", count));
    } else
        collect_folder_names(store, this.folderInfos, store.getDefaultFolder());

    folderBeingScanned = "";

    if (connectOptions.server.endsWith(".pobox.stanford.edu"))
        this.folderInfos.add(new FolderInfo(getAccountID(), "INBOX", "INBOX", 0)); // hack for stanford imap, it lists INBOX as a dir folder! TOFIX

    doneReadingFolderCounts = true;
}

From source file:edu.stanford.muse.email.ImapPopEmailStore.java

public Pair<Folder, Integer> openFolder(Store store, String fname) throws MessagingException {
    Folder folder = openFolderWithoutCount(store, fname);
    int count = -1; // -1 signals invalid folder
    if (folder != null)
        count = folder.getMessageCount();
    log.info("Opened folder " + Util.blurKeepingExtension(fname) + " message count " + count);
    return new Pair<Folder, Integer>(folder, count);
}

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public boolean fetchmailforattch() throws IOException, MessagingException {
    boolean fetchtest = false;

    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imaps");

    try {//from   ww w . java2  s. c o  m
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(IMapHost, MailId, MailPassword);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        totalmailcount = inbox.getMessageCount();

        Message msg = null;
        for (int i = totalmailcount; i > 0; i--) {
            fromadd = "";
            msg = inbox.getMessage(i);
            Address[] in = msg.getFrom();
            for (Address address : in) {
                fromadd = address.toString() + fromadd;
                //System.out.println("FROM:" + address.toString());
            }
            if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches(
                    "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice"))
                break;
        }

        if (fromadd.equals("'")) {
            log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId);
            return fetchtest;
        }

        //    Multipart mp = (Multipart) msg.getContent();
        //  BodyPart bp = mp.getBodyPart(0);
        sentdate = msg.getSentDate().toString();

        subject = msg.getSubject();

        Content = msg.getContent().toString();

        log.log(Level.INFO, Content);
        log.log(Level.INFO, sentdate);
        localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data...");
        LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent);

        Multipart multipart = (Multipart) msg.getContent();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null
                    || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) {
                continue; // dealing with attachments only
            }
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            InputStream is = bodyPart.getInputStream();
            //validvgbinary = IOUtils.toByteArray(is);
            int nRead;
            byte[] data = new byte[5000000];

            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();

            validvgbinary = buffer.toByteArray();
            break;
        }

        fetchtest = true;
    } catch (Exception mex) {
        mex.printStackTrace();

    }

    return fetchtest;
}