Example usage for javax.mail.search FromStringTerm FromStringTerm

List of usage examples for javax.mail.search FromStringTerm FromStringTerm

Introduction

In this page you can find the example usage for javax.mail.search FromStringTerm FromStringTerm.

Prototype

public FromStringTerm(String pattern) 

Source Link

Document

Constructor.

Usage

From source file:search.java

public static void main(String argv[]) {
    int optind;//from   w w  w .  java2 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:search.java

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

    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:com.sonicle.webtop.mail.bol.model.ImapQuery.java

public static SearchTerm toSearchTerm(String allFlagStrings[], List<Tag> atags, QueryObj query,
        DateTimeZone timezone) {//from  w  ww  .  j ava2  s.c o  m
    SearchTerm searchTerm = null;
    ArrayList<SearchTerm> terms = new ArrayList<SearchTerm>();

    if (query != null) {
        ArrayList<Condition> conditionsList = query.conditions;
        String allText = query.allText;

        if (allText != null && allText.trim().length() > 0) {
            SearchTerm defaultterms[] = toDefaultSearchTerm(allText);
            terms.add(new OrTerm(defaultterms));
        }

        conditionsList.forEach(condition -> {
            String key = condition.keyword;
            String value = condition.value;

            if (key.equals(FROM)) {
                terms.add(new FromStringTerm(value));
            } else if (key.equals(TO)) {
                terms.add(new RecipientStringTerm(Message.RecipientType.TO, value));
            } else if (key.equals(SUBJECT)) {
                terms.add(new SubjectTerm(value));
            } else if (key.equals(MESSAGE)) {
                terms.add(new BodyTerm(value));
            } else if (key.equals(EVERYWHERE)) {
                SearchTerm anyterms[] = toAnySearchTerm(value);
                terms.add(new OrTerm(anyterms));
            } else if (key.equals(AFTER)) {
                Date afterDate = ImapQuery.parseDate(value, timezone);
                terms.add(new ReceivedDateTerm(DateTerm.GE, afterDate));
                terms.add(new SentDateTerm(DateTerm.GE, afterDate));
            } else if (key.equals(BEFORE)) {
                Date beforeDate = ImapQuery.parseDate(value, timezone);
                terms.add(new ReceivedDateTerm(DateTerm.LE, beforeDate));
                terms.add(new SentDateTerm(DateTerm.LE, beforeDate));

            } else if (value.equals(ATTACHMENT)) {

            } else if (value.equals(UNREAD)) {
                terms.add(new FlagTerm(new Flags(Flag.SEEN), false));
            } else if (value.equals(FLAGGED)) {
                FlagTerm fts[] = new FlagTerm[allFlagStrings.length + 1];
                fts[0] = new FlagTerm(new Flags(Flag.FLAGGED), true);
                for (int i = 0; i < allFlagStrings.length; ++i)
                    fts[i + 1] = new FlagTerm(new Flags(allFlagStrings[i]), true);
                terms.add(new OrTerm(fts));
            } else if (value.equals(TAGGED)) {
                FlagTerm fts[] = new FlagTerm[atags.size()];
                int i = 0;
                for (Tag tag : atags)
                    fts[i++] = new FlagTerm(new Flags(tag.getTagId()), true);
                terms.add(new OrTerm(fts));
            } else if (value.equals(UNANSWERED)) {
                terms.add(new FlagTerm(new Flags(Flag.ANSWERED), false));
            } else if (value.equals(PRIORITY)) {
                HeaderTerm p1 = new HeaderTerm("X-Priority", "1");
                HeaderTerm p2 = new HeaderTerm("X-Priority", "2");
                terms.add(new OrTerm(p1, p2));
            }

        });
    }

    int n = terms.size();
    if (n == 1) {
        searchTerm = terms.get(0);
    } else if (n > 1) {
        SearchTerm vterms[] = new SearchTerm[n];
        terms.toArray(vterms);
        searchTerm = new AndTerm(vterms);
    }
    return searchTerm;
}

From source file:com.sonicle.webtop.mail.bol.model.ImapQuery.java

public static SearchTerm[] toAnySearchTerm(String value) {
    SearchTerm anyterms[] = new SearchTerm[4];
    anyterms[0] = new SubjectTerm(value);
    anyterms[1] = new RecipientStringTerm(Message.RecipientType.TO, value);
    anyterms[2] = new FromStringTerm(value);
    anyterms[3] = new BodyTerm(value);
    return anyterms;
}

From source file:com.sonicle.webtop.mail.bol.model.ImapQuery.java

public static SearchTerm[] toDefaultSearchTerm(String value) {
    SearchTerm anyterms[] = new SearchTerm[3];
    anyterms[0] = new SubjectTerm(value);
    anyterms[1] = new RecipientStringTerm(Message.RecipientType.TO, value);
    anyterms[2] = new FromStringTerm(value);
    return anyterms;
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

@Override
public GmailMessageList getMessagesBy(EmailSearchStrategy strategy, String value) {
    SearchTerm seekStrategy = null;/*from   w ww.  j  ava 2  s  . com*/
    switch (strategy) {
    case SUBJECT:
        seekStrategy = new SubjectTerm(value);
        LOG.debug("Fetching emails with a subject of \"" + value + "\"");
        break;
    case TO:
        seekStrategy = new RecipientStringTerm(Message.RecipientType.TO, value);
        LOG.debug("Fetching emails sent to \"" + value + "\"");
        break;
    case FROM:
        seekStrategy = new FromStringTerm(value);
        LOG.debug("Fetching emails sent from \"" + value + "\"");
        break;
    case CC:
        seekStrategy = new RecipientStringTerm(Message.RecipientType.CC, value);
        LOG.debug("Fetching emails CC'd to \"" + value + "\"");
        break;
    case DATE_GT:
        seekStrategy = new SentDateTerm(SentDateTerm.GT, parseDate(value));
        LOG.debug("Fetching emails with a send date newer than \"" + value + "\"");
        break;
    case DATE_LT:
        seekStrategy = new SentDateTerm(SentDateTerm.LT, parseDate(value));
        LOG.debug("Fetching emails with a send date newer than \"" + value + "\"");
        break;
    case DATE_EQ:
        seekStrategy = new SentDateTerm(SentDateTerm.EQ, parseDate(value));
        LOG.debug("Fetching emails with a send date newer than \"" + value + "\"");
        break;
    case KEYWORD:
        seekStrategy = new BodyTerm(value);
        LOG.debug("Fetching emails containing the keyword \"" + value + "\"");
        break;
    case UNREAD:
        seekStrategy = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        LOG.debug("Fetching all unread emails");
        break;
    }
    try {
        final GmailMessageList found = new GmailMessageList();
        final Store store = openGmailStore();
        final Folder folder = getFolder(this.srcFolder, store);
        folder.open(Folder.READ_ONLY);
        for (final Message msg : folder.search(seekStrategy)) {
            found.add(new JavaMailGmailMessage(msg));
        }
        LOG.debug("Found " + found.size() + " emails");
        return found;
    } catch (final Exception e) {
        throw new GmailException("Failed getting unread messages", e);
    }
}

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

private static SearchTerm createSearchTerm(MessageListFields searchField, String[] searchValues) {

    SearchTerm[] terms = new SearchTerm[searchValues.length];
    for (int i = 0; i < searchValues.length; i++) {
        if (searchField == MessageListFields.SUBJECT) {
            terms[i] = new SubjectTerm(searchValues[i]);
        } else if (searchField == MessageListFields.FROM) {
            terms[i] = new FromStringTerm(searchValues[i]);
        } else if (searchField == MessageListFields.TO) {
            terms[i] = new RecipientStringTerm(RecipientType.TO, searchValues[i]);
        } else if (searchField == MessageListFields.CC) {
            terms[i] = new RecipientStringTerm(RecipientType.CC, searchValues[i]);
        } else if (searchField == MessageListFields.CONTENT) {
            terms[i] = new BodyTerm(searchValues[i]);
        } else {/*from  w w w  . ja v a 2s.  c  o m*/
            throw new IllegalArgumentException("Search field now allowed: " + searchField.name());
        }
    }

    if (searchValues.length > 1) {
        return new AndTerm(terms);
    } else {
        return terms[0];
    }
}

From source file:org.apache.hupa.server.handler.FetchMessagesHandler.java

@Override
protected MessageConvertArray getMessagesToConvert(com.sun.mail.imap.IMAPFolder f, FetchMessages action)
        throws MessagingException, ActionException {

    String searchString = action.getSearchString();
    int start = action.getStart();
    int offset = action.getOffset();
    int end = start + offset;
    Message[] messages;/*from  w ww  .  j  a va2 s .  com*/
    int exists;
    // check if a searchString was given, and if so use it
    if (searchString == null) {
        exists = f.getMessageCount();

        if (end > exists) {
            end = exists;
        }

        int firstIndex = exists - end + 1;
        if (firstIndex < 1) {
            firstIndex = 1;
        }
        int lastIndex = exists - start;

        messages = f.getMessages(firstIndex, lastIndex);
    } else {
        SearchTerm subjectTerm = new SubjectTerm(searchString);
        SearchTerm fromTerm = new FromStringTerm(searchString);
        SearchTerm bodyTerm = new BodyTerm(searchString);
        SearchTerm orTerm = new OrTerm(new SearchTerm[] { subjectTerm, fromTerm, bodyTerm });
        Message[] tmpMessages = f.search(orTerm);
        if (end > tmpMessages.length) {
            end = tmpMessages.length;
        }
        exists = tmpMessages.length;

        int firstIndex = exists - end;

        if (tmpMessages.length > firstIndex) {
            List<Message> mList = new ArrayList<Message>();
            for (int i = firstIndex; i < tmpMessages.length; i++) {
                if (i == end)
                    break;
                mList.add(tmpMessages[i]);
            }
            messages = mList.toArray(new Message[mList.size()]);
        } else {
            messages = new Message[0];
        }

    }
    logger.debug("Fetching messages for user: " + getUser() + " returns: " + messages.length + " messages in "
            + f.getFullName());

    return new MessageConvertArray(exists, messages);
}

From source file:org.apache.manifoldcf.crawler.connectors.email.EmailConnector.java

private Message[] findMessages(Folder folder, long startTime, long endTime, Map<String, String> findMap)
        throws MessagingException, InterruptedException {
    String findParameterName;/*from w ww . ja  v a2 s.  c o m*/
    String findParameterValue;

    SearchTerm searchTerm = null;

    Iterator<Map.Entry<String, String>> it = findMap.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> pair = it.next();
        findParameterName = pair.getKey().toLowerCase();
        findParameterValue = pair.getValue();
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug(
                    "Email: Finding emails where '" + findParameterName + "' = '" + findParameterValue + "'");
        SearchTerm searchClause = null;
        if (findParameterName.equals(EmailConfig.EMAIL_SUBJECT)) {
            searchClause = new SubjectTerm(findParameterValue);
        } else if (findParameterName.equals(EmailConfig.EMAIL_FROM)) {
            searchClause = new FromStringTerm(findParameterValue);
        } else if (findParameterName.equals(EmailConfig.EMAIL_TO)) {
            searchClause = new RecipientStringTerm(Message.RecipientType.TO, findParameterValue);
        } else if (findParameterName.equals(EmailConfig.EMAIL_BODY)) {
            searchClause = new BodyTerm(findParameterValue);
        }

        if (searchClause != null) {
            if (searchTerm == null)
                searchTerm = searchClause;
            else
                searchTerm = new AndTerm(searchTerm, searchClause);
        } else {
            Logging.connectors.warn("Email: Unknown filter parameter name: '" + findParameterName + "'");
        }
    }

    Message[] result;
    if (searchTerm == null) {
        GetMessagesThread gmt = new GetMessagesThread(session, folder);
        gmt.start();
        result = gmt.finishUp();
    } else {
        SearchMessagesThread smt = new SearchMessagesThread(session, folder, searchTerm);
        smt.start();
        result = smt.finishUp();
    }
    return result;
}

From source file:org.exist.xquery.modules.mail.MessageListFunctions.java

private SearchTerm parseFromTerm(Node terms) throws XPathException {
    SearchTerm st = null;/*from   w ww .  j a  va2 s.c o m*/

    String pattern = ((Element) terms).getAttribute("pattern");

    if (pattern != null && pattern.length() > 0) {
        st = new FromStringTerm(pattern);
    } else {
        throw (new XPathException(this, "Pattern attribute must be specified for term with type: "
                + ((Element) terms).getAttribute("type")));
    }

    return (st);
}