javax.mail.search.AndTerm Java Examples

The following examples show how to use javax.mail.search.AndTerm. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GreenMailServer.java    From micro-integrator with Apache License 2.0 9 votes vote down vote up
/**
 * Check mail folder for an email using subject.
 *
 * @param emailSubject Email subject
 * @param folder       mail folder to check for an email
 * @param protocol     protocol used to connect to the server
 * @return whether mail received or not
 * @throws MessagingException if we're unable to connect to the store
 */
private static boolean isMailReceivedBySubject(String emailSubject, String folder, String protocol,
                                               GreenMailUser user) throws MessagingException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection(user, protocol);
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the Email with Subject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
    } finally {
        if (store != null) {
            store.close();
        }
    }
    return emailReceived;
}
 
Example #2
Source File: GreenMailServer.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Check mail folder for an email using subject.
 *
 * @param emailSubject Email subject
 * @param folder       mail folder to check for an email
 * @param protocol     protocol used to connect to the server
 * @return whether mail received or not
 * @throws MessagingException if we're unable to connect to the store
 */
private static boolean isMailReceivedBySubject(String emailSubject, String folder, String protocol,
        GreenMailUser user) throws MessagingException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection(user, protocol);
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the Email with Subject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
    } finally {
        if (store != null) {
            store.close();
        }
    }
    return emailReceived;
}
 
Example #3
Source File: MailToTransportUtil.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Check a particular email has received to a given email folder by email subject.
 *
 * @param emailSubject - Email emailSubject to find email is in inbox or not
 * @return - found the email or not
 * @throws ESBMailTransportIntegrationTestException - Is thrown if an error occurred while reading the emails
 */
public static boolean isMailReceivedBySubject(String emailSubject, String folder)
        throws ESBMailTransportIntegrationTestException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection();
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the email emailSubject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
        return emailReceived;
    } catch (MessagingException ex) {
        log.error("Error when getting mail count ", ex);
        throw new ESBMailTransportIntegrationTestException("Error when getting mail count ", ex);
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                log.warn("Error when closing the store ", e);
            }
        }
    }
}
 
Example #4
Source File: MailConnection.java    From hop with Apache License 2.0 5 votes vote down vote up
/**
 * Add search term.
 *
 * @param term search term to add
 */
private void addSearchTerm( SearchTerm term ) {
  if ( this.searchTerm != null ) {
    this.searchTerm = new AndTerm( this.searchTerm, term );
  } else {
    this.searchTerm = term;
  }
}
 
Example #5
Source File: MailConnection.java    From hop with Apache License 2.0 5 votes vote down vote up
public void setReceivedDateTermBetween( Date beginDate, Date endDate ) {
  if ( this.protocol == MailConnectionMeta.PROTOCOL_POP3 ) {
    log.logError( BaseMessages.getString( PKG, "MailConnection.Error.ReceivedDatePOP3Unsupported" ) );
  } else {
    addSearchTerm( new AndTerm( new ReceivedDateTerm( ComparisonTerm.LT, endDate ), new ReceivedDateTerm(
      ComparisonTerm.GT, beginDate ) ) );
  }
}
 
Example #6
Source File: MailSteps.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Valid activation email.
 *
 * @param mailHost
 *            example: imap.gmail.com
 * @param mailUser
 *            login of mail box
 * @param mailPassword
 *            password of mail box
 * @param senderMail
 *            sender of mail box
 * @param subjectMail
 *            subject of mail box
 * @param firstCssQuery
 *            the first matching element
 * @param conditions
 *            list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
 * @throws TechnicalException
 *             is throws if you have a technical error (format, configuration, datas, ...) in NoraUi.
 *             Exception with message and with screenshot and with exception if functional error but no screenshot and no exception if technical error.
 * @throws FailureException
 *             if the scenario encounters a functional error
 */
@Experimental(name = "validActivationEmail")
@RetryOnFailure(attempts = 3, delay = 60)
@Conditioned
@Et("Je valide le mail d'activation {string}(\\?)")
@And("I valid activation email {string}(\\?)")
public void validActivationEmail(String mailHost, String mailUser, String mailPassword, String senderMail, String subjectMail, String firstCssQuery, List<GherkinStepCondition> conditions)
        throws FailureException, TechnicalException {
    try {
        final Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imap");
        final Session session = Session.getDefaultInstance(props, null);
        final Store store = session.getStore("imaps");
        store.connect(mailHost, mailUser, mailPassword);
        final Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        final SearchTerm filterA = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        final SearchTerm filterB = new FromTerm(new InternetAddress(senderMail));
        final SearchTerm filterC = new SubjectTerm(subjectMail);
        final SearchTerm[] filters = { filterA, filterB, filterC };
        final SearchTerm searchTerm = new AndTerm(filters);
        final Message[] messages = inbox.search(searchTerm);
        for (final Message message : messages) {
            validateActivationLink(subjectMail, firstCssQuery, message);
        }
    } catch (final Exception e) {
        new Result.Failure<>("", Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_MAIL_ACTIVATION), subjectMail), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
    }
}
 
Example #7
Source File: MailToTransportUtil.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Check a particular email has received to a given email folder by email subject.
 *
 * @param emailSubject - Email emailSubject to find email is in inbox or not
 * @return - found the email or not
 * @throws ESBMailTransportIntegrationTestException - Is thrown if an error occurred while reading the emails
 */
public static boolean isMailReceivedBySubject(String emailSubject, String folder)
        throws ESBMailTransportIntegrationTestException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection();
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the email emailSubject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
        return emailReceived;
    } catch (MessagingException ex) {
        log.error("Error when getting mail count ", ex);
        throw new ESBMailTransportIntegrationTestException("Error when getting mail count ", ex);
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                log.warn("Error when closing the store ", e);
            }
        }
    }
}
 
Example #8
Source File: MailConnection.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
/**
 * Add search term.
 *
 * @param term
 *          search term to add
 */
private void addSearchTerm( SearchTerm term ) {
  if ( this.searchTerm != null ) {
    this.searchTerm = new AndTerm( this.searchTerm, term );
  } else {
    this.searchTerm = term;
  }
}
 
Example #9
Source File: MailConnection.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public void setReceivedDateTermBetween( Date beginDate, Date endDate ) {
  if ( this.protocol == MailConnectionMeta.PROTOCOL_POP3 ) {
    log.logError( BaseMessages.getString( PKG, "MailConnection.Error.ReceivedDatePOP3Unsupported" ) );
  } else {
    addSearchTerm( new AndTerm( new ReceivedDateTerm( ComparisonTerm.LT, endDate ), new ReceivedDateTerm(
      ComparisonTerm.GT, beginDate ) ) );
  }
}
 
Example #10
Source File: SearchCommandParser.java    From greenmail with Apache License 2.0 4 votes vote down vote up
/**
 * Parses the request argument into a valid search term. Not yet fully implemented - see SearchKey enum.
 * <p>
 * Other searches will return everything for now.
 *
 * Throws an UnsupportedCharsetException if provided CHARSET is not supported.
 */
public SearchTerm searchTerm(ImapRequestLineReader request)
        throws ProtocolException {
    Charset charset = StandardCharsets.US_ASCII; // Default
    // Stack contains mix of SearchOperator and SearchTerm instances
    // and will be processed in two steps
    Deque<Object> stack = new LinkedList<>();
    stack.push(SearchOperator.GROUP); // So that the final list of terms will be wrapped in an AndTerm

    // Phase one : parse search query into SearchOperators/simple search terms and put them on the stack.
    char next;
    while ((next = request.nextChar()) != '\n' && next != CHR_CR /* \r */) {
        next = request.consumeAll(CHR_SPACE);

        if (isAtomSpecial(next)) {
            // Parentheses?
            if (next == '(') {
                request.consume();
                request.consumeAll(CHR_SPACE);

                stack.push(SearchOperator.GROUP);
            } else if (next == ')') {
                request.consume();
                request.consumeAll(CHR_SPACE);

                List<SearchTerm> groupItems = new ArrayList<>();
                Object item;
                while ((item = stack.pop()) != SearchOperator.GROUP) {
                    groupItems.add((SearchTerm) item);
                }
                if (groupItems.size() == 1) {
                    stack.push(groupItems.get(0)); // Single item
                } else {
                    stack.push(new AndTerm(groupItems.toArray(new SearchTerm[0])));
                }
            } else {
                throw new IllegalStateException("Unsupported atom special char <" + next + ">");
            }
        } else {
            String token = atomOnly(request);
            // Sequence-set?
            if (SEQUENCE.matcher(token).matches()) {
                stack.push(SearchTermBuilder.create(SearchKey.SEQUENCE_SET).addParameter(token).build());
            }
            // Charset?
            else if (CHARSET_TOKEN.equals(token)) {
                // If the server does not support the specified [CHARSET], it MUST
                // return a tagged NO response (not a BAD).  This response SHOULD
                // contain the BADCHARSET response code, which MAY list the
                // [CHARSET]s supported by the server.
                request.consumeAll(CHR_SPACE);
                final String charsetName = astring(request);
                try {
                    charset = Charset.forName(charsetName);
                } catch (UnsupportedCharsetException ex) {
                    log.error("Unsupported charset '{}", charsetName);
                    throw ex;
                }
            } else {
                // Term?
                SearchKey key = SearchKey.valueOf(token);
                // Operator?
                if (key == SearchKey.NOT) {
                    stack.push(SearchOperator.NOT);
                } else if (key == SearchKey.OR) {
                    stack.push(SearchOperator.OR);
                } else {
                    // No operator
                    SearchTermBuilder b = SearchTermBuilder.create(key);
                    if (b.expectsParameter()) {
                        for (int pi = 0; pi < key.getNumberOfParameters(); pi++) {
                            request.consumeAll(CHR_SPACE);
                            String paramValue = string(request, charset);
                            b.addParameter(paramValue);
                        }
                    }
                    stack.push(b.build());
                }

            }
        }
    }

    // Phase two : Build search terms by operators
    return handleOperators(stack);
}