Example usage for javax.mail.search SubjectTerm SubjectTerm

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

Introduction

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

Prototype

public SubjectTerm(String pattern) 

Source Link

Document

Constructor.

Usage

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  va2s .c  om*/
    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;//w  ww  .jav a 2s .  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 parseSubjectTerm(Node terms) throws XPathException {
    SearchTerm st = null;/*from   w  w  w. j  a v a2s.  com*/

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

    if (pattern != null && pattern.length() > 0) {
        st = new SubjectTerm(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.jevis.emaildatasource.EmailForTest.java

public void testMail() throws MessagingException {
    List<InputStream> answerList = new ArrayList<InputStream>();

    _userName = "artur.iablokov@envidatec.com";
    _password = "na733aya";
    _host = "imap.1und1.de";

    Properties props = new Properties();
    props.put("mail.debug", "true");
    props.put("mail.store.protocol", "imaps");
    _session = Session.getInstance(props);
    _store = _session.getStore();/*  w ww  .  j  a  va2  s  .c  o m*/
    _store.connect(_host, _userName, _password);
    if (!_store.isConnected()) {
        System.out.println("Connected not possible");
    }
    _folderName = "INBOX"; // TODO
    _folder = _store.getFolder(_folderName);
    _folder.open(Folder.READ_ONLY);

    System.out.println("//////////Folder open!/////");

    InputStream answer = null;

    //channel parameter bekommen
    String sender = "support@jevis.de";
    String subject = "testinfo";
    Date lastReadout = new Date(1459658993827L);
    System.out.println("channel parameters: " + sender + " " + subject + " " + lastReadout);
    //richtige E-Mail(-s) finden
    SearchTerm newerThan = new ReceivedDateTerm(ComparisonTerm.GT, lastReadout);
    SearchTerm senderTerm = null;
    try {
        senderTerm = new FromTerm(new InternetAddress(sender));
    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    SearchTerm subjectTerm = new SubjectTerm(subject);
    SearchTerm andTerm = new AndTerm(newerThan, new AndTerm(senderTerm, subjectTerm));
    System.out.println(andTerm.toString());
    List<Message> messageList = null;
    try {
        messageList = Arrays.asList(_folder.search(andTerm));
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //
    _folder.close(false);
    System.out.println("Folder closed");
    _store.close();
    System.out.println("Store closed");

    /**
     * List<File> attachments = new ArrayList<File>(); for (Message message
     * : messageList) { try { Multipart multipart = (Multipart)
     * message.getContent(); for (int i = 0; i < multipart.getCount(); i++)
     * { BodyPart bodyPart = multipart.getBodyPart(i); if
     * (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) &&
     * !StringUtils.isNotBlank(bodyPart.getFileName())) { // !Checks if a
     * String is not empty (""), not null and not whitespace only. continue;
     * // dealing with attachments only } InputStream is =
     * bodyPart.getInputStream(); File file = new File("/tmp/" +
     * bodyPart.getFileName()); FileOutputStream fos = new
     * FileOutputStream(file); byte[] buf = new byte[4096]; int bytesRead;
     * while ((bytesRead = is.read(buf)) != -1) { fos.write(buf, 0,
     * bytesRead); } fos.close(); attachments.add(file);
        }*
     */

    /*for (int i = 0; i < answerList.size(); i++) {
        System.out.print(answerList.get(i).toString());
        }*/
}

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

/**
 * Set filter on subject./*from w  ww . jav a 2 s.  c  o  m*/
 *
 * @param subject
 *          messages will be filtered on subject
 * @param notTerm
 *          negate condition
 */
public void setSubjectTerm(String subject, boolean notTerm) {
    if (!Utils.isEmpty(subject)) {
        if (notTerm) {
            addSearchTerm(new NotTerm(new SubjectTerm(subject)));
        } else {
            addSearchTerm(new SubjectTerm(subject));
        }
    }
}

From source file:org.wso2.esb.integration.common.utils.MailToTransportUtil.java

/**
 * 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/*  ww w  .ja  v a 2 s  .  c  o  m*/
 * @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);
            }
        }
    }
}

From source file:org.wso2.esb.integration.common.utils.servers.GreenMailServer.java

/**
 * Check mail folder for an email using subject.
 *
 * @param emailSubject Email subject//w  w w. j a va 2s.  co  m
 * @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;
}