Example usage for javax.mail Store getDefaultFolder

List of usage examples for javax.mail Store getDefaultFolder

Introduction

In this page you can find the example usage for javax.mail Store getDefaultFolder.

Prototype

public abstract Folder getDefaultFolder() throws MessagingException;

Source Link

Document

Returns a Folder object that represents the 'root' of the default namespace presented to the user by the Store.

Usage

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

public int checkInbox(int mode) throws MessagingException, IOException {
    int numMessages = 0;

    if (mode == 0) {
        return 0;
    }/* w ww .  java2  s . c  o  m*/

    boolean show = (mode & SHOW_MESSAGES) > 0;
    boolean clear = (mode & CLEAR_MESSAGES) > 0;
    String action = (show ? "Show" : "") + ((show && clear) ? " and " : "") + (clear ? "Clear" : "");

    log.info(action + " INBOX for " + from);

    Store store = session.getStore();

    store.connect();

    Folder root = store.getDefaultFolder();
    Folder inbox = root.getFolder("inbox");

    inbox.open(Folder.READ_WRITE);

    Message[] msgs = inbox.getMessages();

    numMessages = msgs.length;

    if ((msgs.length == 0) && show) {
        log.info("No messages in inbox");
    }

    for (int i = 0; i < msgs.length; i++) {
        MimeMessage msg = (MimeMessage) msgs[i];

        if (show) {
            log.info("    From: " + msg.getFrom()[0]);
            log.info(" Subject: " + msg.getSubject());
            log.info(" Content: " + msg.getContent());
        }

        if (clear) {
            msg.setFlag(Flags.Flag.DELETED, true);
        }
    }

    inbox.close(true);
    store.close();

    return numMessages;
}

From source file:com.google.code.rptm.mailarchive.DefaultMailingListArchive.java

public void retrieveMessages(String mailingList, YearMonth month, MimeMessageProcessor processor,
        MailingListArchiveEventListener eventListener) throws MailingListArchiveException {
    Session session = Session.getDefaultInstance(new Properties());
    try {/*from  w  w w .  j  a  v  a2s .  c  om*/
        Store store = session.getStore(new URLName("mstor:" + getMboxFile(mailingList, month, eventListener)));
        store.connect();
        try {
            Folder folder = store.getDefaultFolder();
            folder.open(Folder.READ_ONLY);
            for (Message msg : folder.getMessages()) {
                if (!processor.processMessage((MimeMessage) msg)) {
                    break;
                }
            }
        } finally {
            store.close();
        }
    } catch (MessagingException ex) {
        throw new MailingListArchiveException("JavaMail exception: " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new MailingListArchiveException("I/O exception: " + ex.getMessage(), ex);
    }
}

From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java

/**
 * {@inheritDoc}/*from  w ww.  java  2 s  .c  o  m*/
 * 
 * @throws MessagingException
 * @see org.xwiki.contrib.mail.IMailReader#readFromStore(java.lang.String)
 */
public Message read(String folder, String messageid) throws MessagingException {
    Store store = getJavamailStore();
    store.connect();

    Folder mailFolder = store.getDefaultFolder().getFolder(folder);
    mailFolder.open(Folder.READ_ONLY);
    Message[] messages = mailFolder.search(new MessageIDTerm(messageid));
    mailFolder.close(false);
    store.close();
    if (messages.length > 0) {
        return messages[0];
    }
    return null;
}

From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java

/**
 * {@inheritDoc}//from   w w w.j  ava 2 s .  co  m
 * 
 * @see org.xwiki.contrib.mail.IMailReader#readFromStore(java.lang.String)
 */
@Override
public List<Message> read(String folder, boolean onlyUnred, int max) throws MessagingException {
    Store store = getJavamailStore();
    store.connect();
    Folder mailFolder = store.getDefaultFolder();
    if (StringUtils.isNotEmpty(folder)) {
        mailFolder = mailFolder.getFolder(folder);
    }
    mailFolder.open(Folder.READ_WRITE);
    Message[] msgsArray = mailFolder.getMessages();
    if (max > 0 && msgsArray.length > max) {
        msgsArray = (Message[]) ArrayUtils.subarray(msgsArray, 0, max);
    }
    List<Message> messages = new ArrayList<Message>(Arrays.asList(msgsArray));
    mailFolder.close(false);
    store.close();
    return messages;
}

From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java

/**
 * @param folder/*from  w  w w .  ja  v  a 2s  .  c  om*/
 * @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.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java

public void read() throws MessagingException, IOException, SearchLibException {
    Store store = null;
    try {/*  ww w. j  a  va  2s  .c o  m*/
        store = getStore();
        connect(store);
        readFolder(store.getDefaultFolder());
    } finally {
        if (store != null)
            store.close();
    }
}

From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java

@Override
public ArrayList<FolderItem> getFolderTree() throws MessagingException {
    getLogger().debug("getFolderTree");

    assert (getMailSource() != null);

    ArrayList<FolderItem> folderItems = new ArrayList<FolderItem>();

    Store store = getJavamailStore();
    store.connect();/* ww w  .jav  a  2  s. c  o m*/
    Folder defaultFolder = store.getDefaultFolder();
    FolderItem item = new FolderItem();
    item.setIndex(0);
    item.setLevel(0);
    item.setName(defaultFolder.getName());
    item.setFullName(defaultFolder.getFullName());
    if ((defaultFolder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
        item.setMessageCount(defaultFolder.getMessageCount());
        item.setUnreadMessageCount(defaultFolder.getUnreadMessageCount());
        item.setNewMessageCount(defaultFolder.getNewMessageCount());
    }
    Folder[] folders = defaultFolder.list("*");
    if (ArrayUtils.isEmpty(folders)) {
        folders = defaultFolder.list();
    }

    getLogger().debug("Found folders {}", ArrayUtils.toString(folders));
    int index = 1;
    int level = 1;
    // TODO not really managing folders here, just listing them
    for (Folder folder : folders) {

        item = new FolderItem();
        item.setIndex(index);
        item.setLevel(level);
        item.setName(folder.getName());
        item.setFullName(folder.getFullName());
        if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
            item.setMessageCount(folder.getMessageCount());
            item.setUnreadMessageCount(folder.getUnreadMessageCount());
            item.setNewMessageCount(folder.getNewMessageCount());
            folderItems.add(item);
        }
    }

    store.close();

    return folderItems;

}

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

/** returns # of messages in folder. -1 if folder cannot be opened.
 * connect should already have been called */
public Folder openFolderWithoutCount(Store store, String fname) throws MessagingException {
    Folder folder = null;//from  w ww  . j a  v  a 2  s . c om

    if (fname == null)
        fname = "INBOX";

    folder = store.getDefaultFolder();
    folder = folder.getFolder(fname);

    if (folder == null)
        throw new RuntimeException("Invalid folder: " + fname);

    log.info("Opening folder " + Util.blurKeepingExtension(fname) + " in r/o mode...");
    try {
        folder.open(Folder.READ_ONLY);
    } catch (MessagingException me) {
        return null;
    }
    return folder;
}

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

/**
 * /*  w w  w.  ja  v  a  2s.com*/
 */
@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.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;
    long startTime = 0;
    long endTime = 0;
    try {/*from w w  w.j  av  a2s. c  o  m*/
        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());
        }
    }
}