Example usage for javax.mail FetchProfile add

List of usage examples for javax.mail FetchProfile add

Introduction

In this page you can find the example usage for javax.mail FetchProfile add.

Prototype

public void add(String headerName) 

Source Link

Document

Add the specified header-field to the list of attributes to be prefetched.

Usage

From source file:uidmsgshow.java

public static void main(String argv[]) {
    long uid = -1;
    int optind;//from  w  ww . ja  va 2 s  .  c om

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println(
                    "Usage: uidmsgshow [-L url] [-T protocol] [-H host] [-U user] [-P password] [-f mailbox] [uid] [-v]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length)
            uid = Long.parseLong(argv[optind]);

        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        // session.setDebug(true);

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        folder = folder.getFolder(mbox);
        if (!folder.exists()) {
            System.out.println(mbox + "  does not exist");
            System.exit(1);
        }

        if (!(folder instanceof UIDFolder)) {
            System.out.println("This Provider or this folder does not support UIDs");
            System.exit(1);
        }

        UIDFolder ufolder = (UIDFolder) folder;

        folder.open(Folder.READ_WRITE);
        int totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (uid == -1) {
            // Attributes & Flags for ALL messages ..
            Message[] msgs = ufolder.getMessagesByUID(1, UIDFolder.LASTUID);

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE UID #" + ufolder.getUID(msgs[i]) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            System.out.println("Getting message UID: " + uid);
            Message m = ufolder.getMessageByUID(uid);
            if (m != null)
                dumpPart(m);
            else
                System.out.println("This Message does not exist on this folder");
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
    }
    System.exit(1);
}

From source file:search.java

public static void main(String argv[]) {
    int optind;//from w  w w .  j  a v a  2 s.  com

    String subject = null;
    String from = null;
    boolean or = false;
    boolean today = false;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-or")) {
            or = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-subject")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-from")) {
            from = argv[++optind];
        } else if (argv[optind].equals("-today")) {
            today = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: search [-D] [-L url] [-T protocol] [-H host] "
                    + "[-U user] [-P password] [-f mailbox] "
                    + "[-subject subject] [-from from] [-or] [-today]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {

        if ((subject == null) && (from == null) && !today) {
            System.out.println("Specify either -subject, -from or -today");
            System.exit(1);
        }

        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("Cant find default namespace");
            System.exit(1);
        }

        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        folder.open(Folder.READ_ONLY);
        SearchTerm term = null;

        if (subject != null)
            term = new SubjectTerm(subject);
        if (from != null) {
            FromStringTerm fromTerm = new FromStringTerm(from);
            if (term != null) {
                if (or)
                    term = new OrTerm(term, fromTerm);
                else
                    term = new AndTerm(term, fromTerm);
            } else
                term = fromTerm;
        }
        if (today) {
            ReceivedDateTerm dateTerm = new ReceivedDateTerm(ComparisonTerm.EQ, new Date());
            if (term != null) {
                if (or)
                    term = new OrTerm(term, dateTerm);
                else
                    term = new AndTerm(term, dateTerm);
            } else
                term = dateTerm;
        }

        Message[] msgs = folder.search(term);
        System.out.println("FOUND " + msgs.length + " MESSAGES");
        if (msgs.length == 0) // no match
            System.exit(1);

        // Use a suitable FetchProfile
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        folder.fetch(msgs, fp);

        for (int i = 0; i < msgs.length; i++) {
            System.out.println("--------------------------");
            System.out.println("MESSAGE #" + (i + 1) + ":");
            dumpPart(msgs[i]);
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
    }

    System.exit(1);
}

From source file:search.java

public static void main(String argv[]) {
    int optind;/*from   ww w.j  av  a 2 s .  c  o  m*/

    String subject = null;
    String from = null;
    boolean or = false;
    boolean today = false;
    int size = -1;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-or")) {
            or = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-subject")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-from")) {
            from = argv[++optind];
        } else if (argv[optind].equals("-today")) {
            today = true;
        } else if (argv[optind].equals("-size")) {
            size = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: search [-D] [-L url] [-T protocol] [-H host] "
                    + "[-U user] [-P password] [-f mailbox] "
                    + "[-subject subject] [-from from] [-or] [-today]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {

        if ((subject == null) && (from == null) && !today && size < 0) {
            System.out.println("Specify either -subject, -from, -today, or -size");
            System.exit(1);
        }

        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("Cant find default namespace");
            System.exit(1);
        }

        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        folder.open(Folder.READ_ONLY);
        SearchTerm term = null;

        if (subject != null)
            term = new SubjectTerm(subject);
        if (from != null) {
            FromStringTerm fromTerm = new FromStringTerm(from);
            if (term != null) {
                if (or)
                    term = new OrTerm(term, fromTerm);
                else
                    term = new AndTerm(term, fromTerm);
            } else
                term = fromTerm;
        }
        if (today) {
            Calendar c = Calendar.getInstance();
            c.set(Calendar.HOUR, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
            c.set(Calendar.AM_PM, Calendar.AM);
            ReceivedDateTerm startDateTerm = new ReceivedDateTerm(ComparisonTerm.GE, c.getTime());
            c.add(Calendar.DATE, 1); // next day
            ReceivedDateTerm endDateTerm = new ReceivedDateTerm(ComparisonTerm.LT, c.getTime());
            SearchTerm dateTerm = new AndTerm(startDateTerm, endDateTerm);
            if (term != null) {
                if (or)
                    term = new OrTerm(term, dateTerm);
                else
                    term = new AndTerm(term, dateTerm);
            } else
                term = dateTerm;
        }

        if (size >= 0) {
            SizeTerm sizeTerm = new SizeTerm(ComparisonTerm.GT, size);
            if (term != null) {
                if (or)
                    term = new OrTerm(term, sizeTerm);
                else
                    term = new AndTerm(term, sizeTerm);
            } else
                term = sizeTerm;
        }

        Message[] msgs = folder.search(term);
        System.out.println("FOUND " + msgs.length + " MESSAGES");
        if (msgs.length == 0) // no match
            System.exit(1);

        // Use a suitable FetchProfile
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        folder.fetch(msgs, fp);

        for (int i = 0; i < msgs.length; i++) {
            System.out.println("--------------------------");
            System.out.println("MESSAGE #" + (i + 1) + ":");
            dumpPart(msgs[i]);
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
    }

    System.exit(1);
}

From source file:msgshow.java

public static void main(String argv[]) {
    int optind;//from  w w w . j  a v a 2  s . c o m
    InputStream msgStream = System.in;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-p")) {
            port = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("-s")) {
            showStructure = true;
        } else if (argv[optind].equals("-S")) {
            saveAttachments = true;
        } else if (argv[optind].equals("-m")) {
            showMessage = true;
        } else if (argv[optind].equals("-a")) {
            showAlert = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
            System.out.println("\t[-P password] [-f mailbox] [msgnum ...] [-v] [-D] [-s] [-S] [-a]");
            System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        if (showMessage) {
            MimeMessage msg;
            if (mbox != null)
                msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox)));
            else
                msg = new MimeMessage(session, msgStream);
            dumpPart(msg);
            System.exit(0);
        }

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            if (showAlert) {
                store.addStoreListener(new StoreListener() {
                    public void notification(StoreEvent e) {
                        String s;
                        if (e.getMessageType() == StoreEvent.ALERT)
                            s = "ALERT: ";
                        else
                            s = "NOTICE: ";
                        System.out.println(s + e.getMessage());
                    }
                });
            }
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, port, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        if (mbox == null)
            mbox = "INBOX";
        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        // 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 totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (optind >= argv.length) {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            while (optind < argv.length) {
                int msgnum = Integer.parseInt(argv[optind++]);
                System.out.println("Getting message number: " + msgnum);
                Message m = null;

                try {
                    m = folder.getMessage(msgnum);
                    dumpPart(m);
                } catch (IndexOutOfBoundsException iex) {
                    System.out.println("Message number out of range");
                }
            }
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}

From source file:MainClass.java

public static void main(String argv[]) {
    int msgnum = -1;
    int optind;//from www.  ja  v  a2s. com
    InputStream msgStream = System.in;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-p")) {
            port = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("-s")) {
            showStructure = true;
        } else if (argv[optind].equals("-S")) {
            saveAttachments = true;
        } else if (argv[optind].equals("-m")) {
            showMessage = true;
        } else if (argv[optind].equals("-a")) {
            showAlert = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
            System.out.println("\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]");
            System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length)
            msgnum = Integer.parseInt(argv[optind]);

        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        if (showMessage) {
            MimeMessage msg;
            if (mbox != null)
                msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox)));
            else
                msg = new MimeMessage(session, msgStream);
            dumpPart(msg);
            System.exit(0);
        }

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            if (showAlert) {
                store.addStoreListener(new StoreListener() {
                    public void notification(StoreEvent e) {
                        String s;
                        if (e.getMessageType() == StoreEvent.ALERT)
                            s = "ALERT: ";
                        else
                            s = "NOTICE: ";
                        System.out.println(s + e.getMessage());
                    }
                });
            }
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, port, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        if (mbox == null)
            mbox = "INBOX";
        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        // 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 totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (msgnum == -1) {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            System.out.println("Getting message number: " + msgnum);
            Message m = null;

            try {
                m = folder.getMessage(msgnum);
                dumpPart(m);
            } catch (IndexOutOfBoundsException iex) {
                System.out.println("Message number out of range");
            }
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}

From source file:org.nuxeo.ecm.platform.mail.utils.MailCoreHelper.java

protected static void doCheckMail(DocumentModel currentMailFolder, CoreSession coreSession)
        throws MessagingException {
    String email = (String) currentMailFolder.getPropertyValue(EMAIL_PROPERTY_NAME);
    String password = (String) currentMailFolder.getPropertyValue(PASSWORD_PROPERTY_NAME);
    if (!StringUtils.isEmpty(email) && !StringUtils.isEmpty(password)) {
        mailService = getMailService();//from ww  w. j a va 2s. com

        MessageActionPipe pipe = mailService.getPipe(PIPE_NAME);

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

        // initialize context
        ExecutionContext initialExecutionContext = new ExecutionContext();

        initialExecutionContext.put(MIMETYPE_SERVICE_KEY, getMimeService());

        initialExecutionContext.put(PARENT_PATH_KEY, currentMailFolder.getPathAsString());

        initialExecutionContext.put(CORE_SESSION_KEY, coreSession);

        initialExecutionContext.put(LEAVE_ON_SERVER_KEY, Boolean.TRUE); // TODO should be an attribute in 'protocol'
                                                                        // schema

        Folder rootFolder = null;
        Store store = null;
        try {
            String protocolType = (String) currentMailFolder.getPropertyValue(PROTOCOL_TYPE_PROPERTY_NAME);
            initialExecutionContext.put(PROTOCOL_TYPE_KEY, protocolType);
            // log.debug(PROTOCOL_TYPE_KEY + ": " + (String) initialExecutionContext.get(PROTOCOL_TYPE_KEY));

            String host = (String) currentMailFolder.getPropertyValue(HOST_PROPERTY_NAME);
            String port = (String) currentMailFolder.getPropertyValue(PORT_PROPERTY_NAME);
            Boolean socketFactoryFallback = (Boolean) currentMailFolder
                    .getPropertyValue(SOCKET_FACTORY_FALLBACK_PROPERTY_NAME);
            String socketFactoryPort = (String) currentMailFolder
                    .getPropertyValue(SOCKET_FACTORY_PORT_PROPERTY_NAME);
            Boolean starttlsEnable = (Boolean) currentMailFolder
                    .getPropertyValue(STARTTLS_ENABLE_PROPERTY_NAME);
            String sslProtocols = (String) currentMailFolder.getPropertyValue(SSL_PROTOCOLS_PROPERTY_NAME);
            Long emailsLimit = (Long) currentMailFolder.getPropertyValue(EMAILS_LIMIT_PROPERTY_NAME);
            long emailsLimitLongValue = emailsLimit == null ? EMAILS_LIMIT_DEFAULT : emailsLimit.longValue();

            String imapDebug = Framework.getProperty(IMAP_DEBUG, "false");

            Properties properties = new Properties();
            properties.put("mail.store.protocol", protocolType);
            // properties.put("mail.host", host);
            // Is IMAP connection
            if (IMAP.equals(protocolType)) {
                properties.put("mail.imap.host", host);
                properties.put("mail.imap.port", port);
                properties.put("mail.imap.starttls.enable", starttlsEnable.toString());
                properties.put("mail.imap.debug", imapDebug);
                properties.put("mail.imap.partialfetch", "false");
            } else if (IMAPS.equals(protocolType)) {
                properties.put("mail.imaps.host", host);
                properties.put("mail.imaps.port", port);
                properties.put("mail.imaps.starttls.enable", starttlsEnable.toString());
                properties.put("mail.imaps.ssl.protocols", sslProtocols);
                properties.put("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                properties.put("mail.imaps.socketFactory.fallback", socketFactoryFallback.toString());
                properties.put("mail.imaps.socketFactory.port", socketFactoryPort);
                properties.put("mail.imap.partialfetch", "false");
                properties.put("mail.imaps.partialfetch", "false");
            } else if (POP3S.equals(protocolType)) {
                properties.put("mail.pop3s.host", host);
                properties.put("mail.pop3s.port", port);
                properties.put("mail.pop3s.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                properties.put("mail.pop3s.socketFactory.fallback", socketFactoryFallback.toString());
                properties.put("mail.pop3s.socketFactory.port", socketFactoryPort);
                properties.put("mail.pop3s.ssl.protocols", sslProtocols);
            } else {
                // Is POP3 connection
                properties.put("mail.pop3.host", host);
                properties.put("mail.pop3.port", port);
            }

            properties.put("user", email);
            properties.put("password", password);

            Session session = Session.getInstance(properties);

            store = session.getStore();
            store.connect(email, password);

            String folderName = INBOX; // TODO should be an attribute in 'protocol' schema
            rootFolder = store.getFolder(folderName);

            // need RW access to update message flags
            rootFolder.open(Folder.READ_WRITE);

            Message[] allMessages = rootFolder.getMessages();
            // VDU
            log.debug("nbr of messages in folder:" + allMessages.length);

            FetchProfile fetchProfile = new FetchProfile();
            fetchProfile.add(FetchProfile.Item.FLAGS);
            fetchProfile.add(FetchProfile.Item.ENVELOPE);
            fetchProfile.add(FetchProfile.Item.CONTENT_INFO);
            fetchProfile.add("Message-ID");
            fetchProfile.add("Content-Transfer-Encoding");

            rootFolder.fetch(allMessages, fetchProfile);

            if (rootFolder instanceof IMAPFolder) {
                // ((IMAPFolder)rootFolder).doCommand(FetchProfile)
            }

            List<Message> unreadMessagesList = new ArrayList<Message>();
            for (Message message : allMessages) {
                Flags flags = message.getFlags();
                int unreadMessagesListSize = unreadMessagesList.size();
                if (flags != null && !flags.contains(Flag.SEEN)
                        && unreadMessagesListSize < emailsLimitLongValue) {
                    unreadMessagesList.add(message);
                    if (unreadMessagesListSize == emailsLimitLongValue - 1) {
                        break;
                    }
                }
            }

            Message[] unreadMessagesArray = unreadMessagesList.toArray(new Message[unreadMessagesList.size()]);

            // perform email import
            visitor.visit(unreadMessagesArray, initialExecutionContext);

            // perform flag update globally
            Flags flags = new Flags();
            flags.add(Flag.SEEN);

            boolean leaveOnServer = (Boolean) initialExecutionContext.get(LEAVE_ON_SERVER_KEY);
            if ((IMAP.equals(protocolType) || IMAPS.equals(protocolType)) && leaveOnServer) {
                flags.add(Flag.SEEN);
            } else {
                flags.add(Flag.DELETED);
            }
            rootFolder.setFlags(unreadMessagesArray, flags, true);

        } finally {
            if (rootFolder != null && rootFolder.isOpen()) {
                rootFolder.close(true);
            }
            if (store != null) {
                store.close();
            }
        }
    }
}

From source file:com.cubusmail.server.mail.util.MessageUtils.java

/**
 * @param complete/* ww  w  . j  a  v a  2s  . com*/
 * @param sortfield
 * @return
 */
public static FetchProfile createFetchProfile(boolean complete, MessageListFields sortfield) {

    FetchProfile fp = new FetchProfile();
    if (complete) {
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfile.Item.FLAGS);
        fp.add(FetchProfile.Item.CONTENT_INFO);
        fp.add(IMAPFolder.FetchProfileItem.SIZE);
        fp.add(CubusConstants.FETCH_ITEM_PRIORITY);
        fp.add(UIDFolder.FetchProfileItem.UID);
    } else {
        if (sortfield != null) {
            if (MessageListFields.SUBJECT == sortfield || MessageListFields.FROM == sortfield
                    || MessageListFields.TO == sortfield || MessageListFields.SEND_DATE == sortfield) {
                fp.add(FetchProfile.Item.ENVELOPE);
            } else if (MessageListFields.SIZE == sortfield) {
                fp.add(IMAPFolder.FetchProfileItem.SIZE);
            }
        }
    }
    return fp;
}

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * @param complete/*from ww w. j a v  a  2s.c  om*/
 * @param sortfield
 * @return
 */
public static FetchProfile createFetchProfile(boolean complete, String sortfield) {

    FetchProfile fp = new FetchProfile();
    if (complete) {
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfile.Item.FLAGS);
        fp.add(FetchProfile.Item.CONTENT_INFO);
        fp.add(IMAPFolder.FetchProfileItem.SIZE);
        fp.add(CubusConstants.FETCH_ITEM_PRIORITY);
        fp.add(UIDFolder.FetchProfileItem.UID);
    } else {
        if (sortfield != null) {
            if (MessageListFields.ATTACHMENT_FLAG.name().equals(sortfield)) {
                fp.add(FetchProfile.Item.CONTENT_INFO);
            } else if (MessageListFields.SUBJECT.name().equals(sortfield)
                    || MessageListFields.FROM.name().equals(sortfield)
                    || MessageListFields.TO.name().equals(sortfield)
                    || MessageListFields.DATE.name().equals(sortfield)) {
                fp.add(FetchProfile.Item.ENVELOPE);
            } else if (MessageListFields.SIZE.name().equals(sortfield)) {
                fp.add(IMAPFolder.FetchProfileItem.SIZE);
            }
        }
    }
    return fp;
}

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();// ww w .j a v  a  2s  .  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:com.silverpeas.mailinglist.service.job.TestYahooMailConnection.java

@Test
public void testOpenImapConnection() throws Exception {
    Store mailAccount = null;// w  ww.  jav a2  s .co  m
    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();
        }
    }
}