Search in sources :

Example 11 with SubjectTerm

use of javax.mail.search.SubjectTerm in project opentest by mcdcorp.

the class ReadEmailImap method run.

@Override
public void run() {
    super.run();
    final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);
    String defaultSentAfterTime = LocalDateTime.now().minusDays(365).format(dateTimeFormatter);
    String imapServer = this.readStringArgument("server");
    Integer port = this.readIntArgument("port", null);
    String subjectContains = this.readStringArgument("subjectContains", this.readStringArgument("subject", null));
    Pattern subjectRegex = this.readRegexArgument("subjectRegex", null);
    String bodyContains = this.readStringArgument("bodyContains", null);
    Pattern bodyRegex = this.readRegexArgument("bodyRegex", null);
    String fromAddress = this.readStringArgument("from", null);
    String sentAfter = this.readStringArgument("sentAfter", defaultSentAfterTime);
    String userName = this.readStringArgument("userName");
    String password = this.readStringArgument("password");
    Integer maxResults = this.readIntArgument("maxResults", 1);
    Integer minResults = this.readIntArgument("minResults", 1);
    LocalDateTime sentAfterDate = LocalDateTime.parse(sentAfter, dateTimeFormatter);
    ZonedDateTime sentAfterZonedDate = ZonedDateTime.of(sentAfterDate, ZoneId.systemDefault());
    Folder inbox = null;
    Store store = null;
    try {
        Session session = Session.getDefaultInstance(System.getProperties());
        store = session.getStore("imaps");
        if (port == null) {
            store.connect(imapServer, userName, password);
        } else {
            store.connect(imapServer, port, userName, password);
        }
        inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        SentDateTerm sentDateTerm = new SentDateTerm(ComparisonTerm.GE, Date.from(sentAfterZonedDate.toInstant()));
        SearchTerm searchTerm = sentDateTerm;
        if (subjectContains != null) {
            SubjectTerm subjectTerm = new SubjectTerm(subjectContains);
            searchTerm = new AndTerm(searchTerm, subjectTerm);
        }
        if (bodyContains != null) {
            BodyTerm bodyTerm = new BodyTerm(bodyContains);
            searchTerm = new AndTerm(searchTerm, bodyTerm);
        }
        if (fromAddress != null) {
            FromStringTerm fromTerm = new FromStringTerm(fromAddress);
            searchTerm = new AndTerm(searchTerm, fromTerm);
        }
        List<Message> allMessages = Arrays.asList(inbox.search(searchTerm));
        int resultsIndex = 0;
        ArrayList<HashMap<String, String>> resultMessages = new ArrayList<>();
        while (resultMessages.size() < maxResults) {
            resultsIndex++;
            if (resultsIndex > allMessages.size()) {
                break;
            }
            Message currentMessage = allMessages.get(allMessages.size() - resultsIndex);
            // Make sure the sent date and time is after the specified
            // one. Since javax.mail only takes the date into consideration
            // and ignores the time, we might end up with messages sent earlier
            // than the time specified, so we must check this ourselves
            boolean sentDateIsInRange = currentMessage.getSentDate().after(Date.from(sentAfterZonedDate.toInstant()));
            if (!sentDateIsInRange) {
                continue;
            }
            String subject = currentMessage.getSubject();
            if (subjectRegex != null && !subjectRegex.matcher(subject).find()) {
                continue;
            }
            String body = this.getTextFromMessage(currentMessage);
            if (bodyRegex != null && !bodyRegex.matcher(body).find()) {
                continue;
            }
            HashMap resultMessage = new HashMap<>();
            resultMessage.put("subject", subject);
            resultMessage.put("body", body);
            resultMessage.put("from", getEmailAddresses(currentMessage.getFrom()));
            resultMessage.put("to", getEmailAddresses(currentMessage.getAllRecipients()));
            LocalDateTime sentDate = LocalDateTime.ofInstant(currentMessage.getSentDate().toInstant(), ZoneId.systemDefault());
            resultMessage.put("sentDate", sentDate.format(dateTimeFormatter));
            HashMap<String, String> headers = new HashMap<>();
            Enumeration headersIterator = currentMessage.getAllHeaders();
            while (headersIterator.hasMoreElements()) {
                Header header = (Header) headersIterator.nextElement();
                headers.put(header.getName(), header.getValue());
            }
            resultMessage.put("headers", headers);
            resultMessages.add(resultMessage);
        }
        if (resultMessages.size() < minResults) {
            throw new RuntimeException(String.format("We were expecting to find at least %s email message(s) matching the " + "given criteria, but we found %s. You can set the minimum number " + "of messages expected by using the \"minResults\" argument.", minResults, resultMessages.size()));
        } else {
            Logger.info(String.format("We found %s email message(s) matching the given criteria", resultMessages.size()));
        }
        this.writeOutput("emails", ScriptUtils.wrapArray(resultMessages.toArray()));
        // Write the details of the most recent message again, to
        // dedicated output values. These three output values will be
        // deprecated and are only populated for backward compatibility.
        HashMap mostRecentMessage = resultMessages.get(0);
        this.writeOutput("subject", mostRecentMessage.get("subject"));
        this.writeOutput("body", mostRecentMessage.get("body"));
        this.writeOutput("from", mostRecentMessage.get("from"));
    } catch (Exception ex) {
        throw new RuntimeException(String.format("Failed to read emails from server %s", imapServer), ex);
    } finally {
        try {
            if (inbox != null) {
                inbox.close(true);
            }
            if (store != null) {
                store.close();
            }
        } catch (MessagingException ex) {
            Logger.error("Failed to close the email store and/or folder", ex);
        }
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) Message(javax.mail.Message) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Store(javax.mail.Store) SentDateTerm(javax.mail.search.SentDateTerm) Folder(javax.mail.Folder) AndTerm(javax.mail.search.AndTerm) ZonedDateTime(java.time.ZonedDateTime) BodyTerm(javax.mail.search.BodyTerm) Pattern(java.util.regex.Pattern) Enumeration(java.util.Enumeration) MessagingException(javax.mail.MessagingException) SearchTerm(javax.mail.search.SearchTerm) SubjectTerm(javax.mail.search.SubjectTerm) MessagingException(javax.mail.MessagingException) FromStringTerm(javax.mail.search.FromStringTerm) Header(javax.mail.Header) DateTimeFormatter(java.time.format.DateTimeFormatter) Session(javax.mail.Session)

Example 12 with SubjectTerm

use of javax.mail.search.SubjectTerm in project alfresco-repository by Alfresco.

the class ImapServiceImplTest method testSearchTerms.

/**
 * MNT-12773
 * @throws AddressException
 */
public void testSearchTerms() throws AddressException {
    List<AlfrescoImapFolder> mf = imapService.listMailboxes(user, IMAP_ROOT + "/" + TEST_IMAP_FOLDER_NAME + "/_*", false);
    ArrayList<Long> res = new ArrayList<Long>();
    SearchTerm st = null;
    st = new SentDateTerm(ComparisonTerm.LT, new Date());
    extractSearchTermResultsToList(mf, st, res);
    assertEquals("Size of mails isn't correct. Search by sent date", 3, res.size());
    res.clear();
    st = new SubjectTerm("For Test");
    extractSearchTermResultsToList(mf, st, res);
    assertEquals("Size of mails isn't correct. Search by subject", 1, res.size());
    res.clear();
    st = new FromTerm(new InternetAddress("admin@alfresco.com"));
    extractSearchTermResultsToList(mf, st, res);
    assertEquals("Size of mails isn't correct. Search by \"From\" term", 1, res.size());
    res.clear();
    st = new AndTerm(st, new SubjectTerm("For Test"));
    extractSearchTermResultsToList(mf, st, res);
    assertEquals("Size of mails isn't correct. Search by \"From\" and \"Subject\" terms", 1, res.size());
}
Also used : AndTerm(javax.mail.search.AndTerm) InternetAddress(javax.mail.internet.InternetAddress) ArrayList(java.util.ArrayList) SentDateTerm(javax.mail.search.SentDateTerm) SearchTerm(javax.mail.search.SearchTerm) FromTerm(javax.mail.search.FromTerm) SubjectTerm(javax.mail.search.SubjectTerm) Date(java.util.Date)

Aggregations

SearchTerm (javax.mail.search.SearchTerm)12 SubjectTerm (javax.mail.search.SubjectTerm)12 AndTerm (javax.mail.search.AndTerm)8 FromStringTerm (javax.mail.search.FromStringTerm)6 InternetAddress (javax.mail.internet.InternetAddress)5 Message (javax.mail.Message)4 URISyntaxException (java.net.URISyntaxException)3 DateFormat (java.text.DateFormat)3 ParseException (java.text.ParseException)3 SimpleDateFormat (java.text.SimpleDateFormat)3 MessagingException (javax.mail.MessagingException)3 MimeMessage (javax.mail.internet.MimeMessage)3 ArrayList (java.util.ArrayList)2 Folder (javax.mail.Folder)2 Session (javax.mail.Session)2 Store (javax.mail.Store)2 FromTerm (javax.mail.search.FromTerm)2 NotTerm (javax.mail.search.NotTerm)2 OrTerm (javax.mail.search.OrTerm)2 SentDateTerm (javax.mail.search.SentDateTerm)2