Example usage for javax.mail.search BodyTerm BodyTerm

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

Introduction

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

Prototype

public BodyTerm(String pattern) 

Source Link

Document

Constructor

Usage

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

public static SearchTerm toSearchTerm(String allFlagStrings[], List<Tag> atags, QueryObj query,
        DateTimeZone timezone) {/*ww  w . j av  a 2s  . 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.googlecode.gmail4j.javamail.ImapGmailClient.java

@Override
public GmailMessageList getMessagesBy(EmailSearchStrategy strategy, String value) {
    SearchTerm seekStrategy = null;/* w  w  w  .j  av a 2s.  co m*/
    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:edu.stanford.muse.email.Filter.java

public SearchTerm convertToSearchTerm(boolean useReceivedDateTerms) {
    // FLAG DEBUG: end date = null
    //endDate = null;
    SearchTerm sentOnlyTerm = null;/* www.j a v  a 2s .co m*/
    if (sentMessagesOnly) {
        List<SearchTerm> fromAddrTerms = new ArrayList<SearchTerm>();
        if (ownCI != null) {
            for (String e : ownCI.emails)
                try {
                    fromAddrTerms.add(new FromTerm(new InternetAddress(e, ""))); // the name doesn't matter for equality of InternetAddress            
                } catch (Exception ex) {
                    Util.print_exception(ex, log);
                }

            // or all the from terms (not and)
            if (fromAddrTerms.size() >= 1) {
                sentOnlyTerm = fromAddrTerms.get(0);
                for (int i = 1; i < fromAddrTerms.size(); i++)
                    sentOnlyTerm = new OrTerm(sentOnlyTerm, fromAddrTerms.get(i));
            }
        }
    }

    SearchTerm result = sentOnlyTerm;

    if (startDate != null) {
        SearchTerm startTerm = useReceivedDateTerms ? new ReceivedDateTerm(ComparisonTerm.GT, startDate)
                : new SentDateTerm(ComparisonTerm.GT, startDate);
        if (result != null)
            result = new AndTerm(result, startTerm);
        else
            result = startTerm;
    }

    if (endDate != null) {
        SearchTerm endTerm = useReceivedDateTerms ? new ReceivedDateTerm(ComparisonTerm.LT, endDate)
                : new SentDateTerm(ComparisonTerm.LT, endDate);
        if (result != null)
            result = new AndTerm(result, endTerm);
        else
            result = endTerm;
    }

    if (keywords != null)
        for (String s : keywords) {
            if (Util.nullOrEmpty(s))
                continue;
            // look for this keyword in both subject and body
            SearchTerm sTerm = new OrTerm(new BodyTerm(s), new SubjectTerm(s));
            if (result != null)
                result = new AndTerm(result, sTerm);
            else
                result = sTerm;
        }
    return result;
}

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 {// w ww.j a v  a 2  s . 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:com.cubusmail.mail.util.MessageUtils.java

/**
 * @param mailFolder/*from  www . jav a2 s .  c  om*/
 * @param msgs
 * @param extendedSearchFields
 * @param params
 * @return
 */
public static Message[] filterMessages(IMailFolder mailFolder, Message[] msgs, String extendedSearchFields,
        String[][] params) {

    if (!StringUtils.isEmpty(extendedSearchFields)) {
        String[] fields = StringUtils.split(extendedSearchFields, ',');

        List<Message> filteredMsgs = new ArrayList<Message>();
        String fromValue = getParamValue(params, SearchFields.FROM.name());
        String toValue = getParamValue(params, SearchFields.TO.name());
        String ccValue = getParamValue(params, SearchFields.CC.name());
        String subjectValue = getParamValue(params, SearchFields.SUBJECT.name());
        String contentValue = getParamValue(params, SearchFields.CONTENT.name());
        String dateFromValue = getParamValue(params, SearchFields.DATE_FROM.name());
        String dateToValue = getParamValue(params, SearchFields.DATE_TO.name());

        try {
            // Body search
            if (StringUtils.contains(extendedSearchFields, SearchFields.CONTENT.name())) {
                BodyTerm term = new BodyTerm(contentValue);
                msgs = mailFolder.search(term, msgs);
                if (msgs == null) {
                    msgs = new Message[0];
                }
            }

            for (Message message : msgs) {
                boolean contains = true;
                for (String searchField : fields) {
                    if (SearchFields.FROM.name().equals(searchField)) {
                        String from = MessageUtils.getMailAdressString(message.getFrom(),
                                AddressStringType.COMPLETE);
                        contains = StringUtils.containsIgnoreCase(from, fromValue);
                    }
                    if (contains && SearchFields.TO.name().equals(searchField)) {
                        String to = MessageUtils.getMailAdressString(
                                message.getRecipients(Message.RecipientType.TO), AddressStringType.COMPLETE);
                        if (!StringUtils.isEmpty(to)) {
                            contains = StringUtils.containsIgnoreCase(to, toValue);
                        } else {
                            contains = false;
                        }
                    }
                    if (contains && SearchFields.CC.name().equals(searchField)) {
                        String cc = MessageUtils.getMailAdressString(
                                message.getRecipients(Message.RecipientType.CC), AddressStringType.COMPLETE);
                        if (!StringUtils.isEmpty(cc)) {
                            contains = StringUtils.containsIgnoreCase(cc, ccValue);
                        } else {
                            contains = false;
                        }
                    }
                    if (contains && SearchFields.SUBJECT.name().equals(searchField)) {
                        if (!StringUtils.isEmpty(message.getSubject())) {
                            contains = StringUtils.containsIgnoreCase(message.getSubject(), subjectValue);
                        } else {
                            contains = false;
                        }
                    }
                    if (contains && SearchFields.DATE_FROM.name().equals(searchField)) {
                        Date dateFrom = new Date(Long.parseLong(dateFromValue));
                        if (message.getSentDate() != null) {
                            contains = !message.getSentDate().before(dateFrom);
                        } else {
                            contains = false;
                        }
                    }
                    if (contains && SearchFields.DATE_TO.name().equals(searchField)) {
                        Date dateTo = new Date(Long.parseLong(dateToValue));
                        if (message.getSentDate() != null) {
                            contains = !message.getSentDate().after(dateTo);
                        } else {
                            contains = false;
                        }
                    }
                }
                if (contains) {
                    filteredMsgs.add(message);
                }
            }
        } catch (MessagingException ex) {
            log.warn(ex.getMessage());
        }

        return filteredMsgs.toArray(new Message[0]);
    }

    return msgs;
}

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 w  w .  j  a v  a2  s.  c o m*/
    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;// ww w .j  a va2 s  . co 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 parseBodyTerm(Node terms) throws XPathException {
    SearchTerm st = null;/* w  ww .  ja v a2s.c om*/

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

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

    return (st);
}

From source file:org.pentaho.di.job.entries.getpop.MailConnection.java

/**
 * Search all messages with body containing the word bodyfilter
 *
 * @param bodyfilter/*from w  w  w .ja  va2 s .  c om*/
 * @param notTerm
 *          negate condition
 */
public void setBodyTerm(String bodyfilter, boolean notTerm) {
    if (!Utils.isEmpty(bodyfilter)) {
        if (notTerm) {
            addSearchTerm(new NotTerm(new BodyTerm(bodyfilter)));
        } else {
            addSearchTerm(new BodyTerm(bodyfilter));
        }
    }
}