List of usage examples for javax.mail Folder search
public Message[] search(SearchTerm term) throws MessagingException
From source file:org.accesointeligente.server.robots.ResponseChecker.java
public void connectAndCheck() { if (ApplicationProperties.getProperty("email.server") == null || ApplicationProperties.getProperty("email.user") == null || ApplicationProperties.getProperty("email.password") == null || ApplicationProperties.getProperty("email.folder") == null || ApplicationProperties.getProperty("email.failfolder") == null || ApplicationProperties.getProperty("attachment.directory") == null || ApplicationProperties.getProperty("attachment.baseurl") == null) { logger.error("Properties are not defined!"); return;/*from ww w .j a va2 s .c o m*/ } org.hibernate.Session hibernate = null; try { session = Session.getInstance(props, null); store = session.getStore("imaps"); store.connect(ApplicationProperties.getProperty("email.server"), ApplicationProperties.getProperty("email.user"), ApplicationProperties.getProperty("email.password")); Folder failbox = store.getFolder(ApplicationProperties.getProperty("email.failfolder")); Folder inbox = store.getFolder(ApplicationProperties.getProperty("email.folder")); inbox.open(Folder.READ_WRITE); for (Message message : inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false))) { try { logger.info("Sender: " + message.getFrom()[0] + "\tSubject: " + message.getSubject()); remoteIdentifiers = null; messageBody = null; remoteIdentifiers = new HashSet<String>(); if (message.getSubject() != null) { Matcher matcher = pattern.matcher(message.getSubject()); if (matcher.matches()) { remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); } } Object content = message.getContent(); if (content instanceof Multipart) { Multipart mp = (Multipart) message.getContent(); logger.info("Email content type is Multipart, each part of " + mp.getCount() + " will be processed"); for (int i = 0, n = mp.getCount(); i < n; i++) { Part part = mp.getBodyPart(i); logger.info("Part: " + (i + 1) + " of " + mp.getCount()); processPart(part); } } else if (content instanceof String) { logger.info("Email content type is String"); messageBody = (String) content; Matcher matcher; StringTokenizer tokenizer = new StringTokenizer(messageBody); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); matcher = pattern.matcher(token); if (matcher.matches()) { remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); } } } else { logger.info("Email content type isn't String or Multipart"); message.setFlag(Flag.SEEN, false); inbox.copyMessages(new Message[] { message }, failbox); message.setFlag(Flag.DELETED, true); inbox.expunge(); continue; } Boolean requestFound = false; Matcher matcher = htmlPattern.matcher(messageBody); if (matcher.find()) { messageBody = htmlToString(messageBody); } logger.info("Searching for Request Remote Identifier"); for (String remoteIdentifier : remoteIdentifiers) { hibernate = HibernateUtil.getSession(); hibernate.beginTransaction(); Criteria criteria = hibernate.createCriteria(Request.class); criteria.add(Restrictions.eq("remoteIdentifier", remoteIdentifier)); Request request = (Request) criteria.uniqueResult(); hibernate.getTransaction().commit(); if (request != null) { logger.info("Request found for Remote Identifier: " + remoteIdentifier); Response response; // If the attachments haven't been used, use them. Otherwise, copy them. if (!requestFound) { response = createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); } else { response = createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); } hibernate = HibernateUtil.getSession(); hibernate.beginTransaction(); response.setRequest(request); request.setStatus(RequestStatus.RESPONDED); request.setExpired(RequestExpireType.WITHRESPONSE); request.setResponseDate(new Date()); hibernate.update(request); hibernate.update(response); hibernate.getTransaction().commit(); requestFound = true; } } if (!requestFound) { logger.info("Request not found"); createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); message.setFlag(Flag.SEEN, false); inbox.copyMessages(new Message[] { message }, failbox); message.setFlag(Flag.DELETED, true); inbox.expunge(); } } catch (Exception e) { if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) { hibernate.getTransaction().rollback(); } logger.error(e.getMessage(), e); } } } catch (Exception e) { if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) { hibernate.getTransaction().rollback(); } logger.error(e.getMessage(), e); } }
From source file:org.exist.xquery.modules.mail.MessageListFunctions.java
private Sequence searchMessageList(Sequence[] args, Sequence contextSequence) throws XPathException { Message[] msgList;//from ww w . ja v a 2 s. c o m // was a folder handle specified? if (args[0].isEmpty() || args[1].isEmpty()) { throw (new XPathException(this, "Folder handle or Search Terms not specified")); } // get the Folder long folderHandle = ((IntegerValue) args[0].itemAt(0)).getLong(); Folder folder = MailModule.retrieveFolder(context, folderHandle); if (folder == null) { throw (new XPathException(this, "Invalid Folder handle specified")); } Node searchTermsXML = ((NodeValue) args[1].itemAt(0)).getNode(); try { msgList = folder.search(parseSearchTerms(searchTermsXML)); prefetchMessages(folder, msgList); } catch (MessagingException me) { throw (new XPathException(this, "Failed to get mail list", me)); } // save the message list and return the handle of the message list return (new IntegerValue(MailModule.storeMessageList(context, msgList, folderHandle))); }
From source file:org.jevis.emaildatasource.EMailManager.java
/** * Get list of messages// w w w . ja v a 2 s .c o m * * @param folder * @param conn * * @return List of Message */ private static List<Message> getMessageList(Folder folder, EMailChannelParameters chanParam) { List<Message> messageList = null; SearchTerm term = chanParam.getSearchTerms(); try { folder.open(Folder.READ_ONLY); } catch (MessagingException ex) { Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE, "EMail folder is not available to read.", ex); } Message[] msgs = null; Logger.getLogger(EMailManager.class.getName()).log(Level.INFO, "Folder is open: {0}", folder.isOpen()); if (chanParam.getProtocol().equalsIgnoreCase(EMailConstants.Protocol.IMAP)) { try { msgs = folder.search(term); } catch (MessagingException ex) { Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE, "Unable to search messages", ex); } } else if (chanParam.getProtocol().equalsIgnoreCase(EMailConstants.Protocol.POP3)) { try { // int[] msgnums = new int[1000]; // Message[] messages = folder.getMessages(msgnums); Message[] messages = folder.getMessages(); messages = filterPOP3ByDate(messages, chanParam.getLastReadout()); msgs = folder.search(term, messages); } catch (MessagingException ex) { Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE, "POP3: failed to receive messages from a folder.", ex); } } else { Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE, "Unable to search messages"); } messageList = Arrays.asList(msgs); Logger.getLogger(EMailManager.class.getName()).log(Level.INFO, "Messages found: {0}", messageList.size()); return messageList; }
From source file:org.nuxeo.cm.event.MailInjectionListener.java
public void handleEvent(Event event) throws ClientException { MailService mailService = Framework.getService(MailService.class); MessageActionPipe pipe = mailService.getPipe(MAILBOX_PIPE); Visitor visitor = new Visitor(pipe); Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader()); Folder rootFolder = null; try (CoreSession session = CoreInstance.openCoreSessionSystem(null)) { // initialize context ExecutionContext initialExecutionContext = new ExecutionContext(); initialExecutionContext.put(AbstractCaseManagementMailAction.CORE_SESSION_KEY, session); initialExecutionContext.put(AbstractCaseManagementMailAction.MIMETYPE_SERVICE_KEY, Framework.getService(MimetypeRegistry.class)); initialExecutionContext.put(AbstractCaseManagementMailAction.CASEMANAGEMENT_SERVICE_KEY, Framework.getService(CaseDistributionService.class)); // open store Store store = mailService.getConnectedStore(IMPORT_MAILBOX); rootFolder = store.getFolder(INBOX); rootFolder.open(Folder.READ_WRITE); Flags flags = new Flags(); flags.add(Flag.SEEN);//from w w w . j ava 2 s . c o m SearchTerm term = new FlagTerm(flags, false); Message[] unreadMessages = rootFolder.search(term); // perform import visitor.visit(unreadMessages, initialExecutionContext); // save session session.save(); if (rootFolder.isOpen()) { try { rootFolder.close(true); } catch (MessagingException e) { log.error(e.getMessage(), e); } } } catch (MessagingException e) { log.error(e, e); } }
From source file:org.opennms.javamail.JavaReadMailer.java
/** * <p>retrieveMessages</p>/*from www.j ava 2s . c o m*/ * * @param term a {@link javax.mail.search.SearchTerm} object. * @return a {@link java.util.List} object. * @throws org.opennms.javamail.JavaMailerException if any. */ public List<Message> retrieveMessages(SearchTerm term) throws JavaMailerException { Message[] msgs; Folder mailFolder = null; try { Store store = m_session.getStore(m_config.getReadmailHost().getReadmailProtocol().getTransport()); store.connect(m_config.getReadmailHost().getHost(), (int) m_config.getReadmailHost().getPort(), m_config.getUserAuth().getUserName(), m_config.getUserAuth().getPassword()); mailFolder = store.getFolder(m_config.getMailFolder()); mailFolder.open(Folder.READ_WRITE); msgs = mailFolder.search(term); } catch (NoSuchProviderException e) { throw new JavaMailerException( "No provider matching:" + m_config.getReadmailHost().getReadmailProtocol().getTransport() + " from config:" + m_config.getName(), e); } catch (MessagingException e) { throw new JavaMailerException("Problem reading messages from configured mail store", e); } List<Message> msgList = Arrays.asList(msgs); return msgList; }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
/** * /*from ww w . j av a 2s. c o m*/ * @param folder * @param messageId * @return */ Message findMsgByMessageId(Folder folder, String messageId) throws MessagingException { Message msg = null; System.out.println("===> findMsgByMessageId: Looking for Message-Id=" + messageId); //DEBUG ONLY //Message[] ms = folder.getMessages(); //FetchProfile fp = new FetchProfile(); //fp.add(IMAPFolder.FetchProfileItem.HEADERS); //folder.fetch(ms, fp); // ///// // int i = 0; // for (Message m : ms) { // ++i; // IMAPMessage im = (IMAPMessage) m; // System.out.println("===> findMsgByMessageId: msg-subject= " // + m.getSubject() + "\n\tIMAPMessage id=" + im.getMessageID()); // // Enumeration headers = ms[i].getAllHeaders(); // while (headers.hasMoreElements()) { // Header h = (Header) headers.nextElement(); // if (h.getName().equalsIgnoreCase("Message-Id")) { // System.out.println("\t" + h.getName() + ": " + h.getValue()); // } // } // System.out.println(); // // } // Prep and search through all msgs in folder for that id. // take the first one found. //SearchTerm st = new HeaderTerm("Message-Id:", messageId) ; SearchTerm st = new javax.mail.search.MessageIDTerm(messageId); Message[] msgs = folder.search(st); if ((msgs != null) && (msgs.length > 0)) { msg = msgs[0]; //this.printMsgIdSubject(msg); //DBG printout } else { System.out.println("===> findMsgByMessageId: Msg NOT FOUND for Message-Id=" + messageId); } return msg; }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@Test // see INT-1801 public void testImapLifecycleForRaceCondition() throws Exception { for (int i = 0; i < 1000; i++) { final ImapMailReceiver receiver = new ImapMailReceiver("imap://foo"); Store store = mock(Store.class); Folder folder = mock(Folder.class); given(folder.exists()).willReturn(true); given(folder.isOpen()).willReturn(true); given(folder.search((SearchTerm) Mockito.any())).willReturn(new Message[] {}); given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder); given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER)); DirectFieldAccessor df = new DirectFieldAccessor(receiver); df.setPropertyValue("store", store); receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet();//from www . ja v a2 s.c om new Thread(() -> { try { receiver.receive(); } catch (javax.mail.MessagingException e) { if (e.getCause() instanceof NullPointerException) { failed.getAndIncrement(); } } }).start(); new Thread(() -> { try { receiver.destroy(); } catch (Exception ignore) { // ignore } }).start(); } assertEquals(0, failed.get()); }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
private Folder testAttachmentsGuts(final ImapMailReceiver receiver) throws MessagingException, IOException { Store store = mock(Store.class); Folder folder = mock(Folder.class); given(folder.exists()).willReturn(true); given(folder.isOpen()).willReturn(true); Message message = new MimeMessage(null, new ClassPathResource("test.mail").getInputStream()); given(folder.search((SearchTerm) Mockito.any())).willReturn(new Message[] { message }); given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder); given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER)); DirectFieldAccessor df = new DirectFieldAccessor(receiver); df.setPropertyValue("store", store); receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet();/*from ww w .jav a 2 s .co m*/ return folder; }
From source file:org.springframework.ws.transport.mail.monitor.AbstractMonitoringStrategy.java
/** * Retrieves new messages from the given folder. This implementation creates a {@link SearchTerm} that searches for * all messages in the folder that are {@link javax.mail.Flags.Flag#RECENT RECENT}, not {@link * javax.mail.Flags.Flag#ANSWERED ANSWERED}, and not {@link javax.mail.Flags.Flag#DELETED DELETED}. The search term * is used to {@link Folder#search(SearchTerm) search} for new messages. * * @param folder the folder to retrieve new messages from * @return the new messages// w w w . j a va 2 s .com * @throws MessagingException in case of JavaMail errors */ protected Message[] searchForNewMessages(Folder folder) throws MessagingException { if (!folder.isOpen()) { return new Message[0]; } Flags supportedFlags = folder.getPermanentFlags(); SearchTerm searchTerm = null; if (supportedFlags != null) { if (supportedFlags.contains(Flags.Flag.RECENT)) { searchTerm = new FlagTerm(new Flags(Flags.Flag.RECENT), true); } if (supportedFlags.contains(Flags.Flag.ANSWERED)) { FlagTerm answeredTerm = new FlagTerm(new Flags(Flags.Flag.ANSWERED), false); if (searchTerm == null) { searchTerm = answeredTerm; } else { searchTerm = new AndTerm(searchTerm, answeredTerm); } } if (supportedFlags.contains(Flags.Flag.DELETED)) { FlagTerm deletedTerm = new FlagTerm(new Flags(Flags.Flag.DELETED), false); if (searchTerm == null) { searchTerm = deletedTerm; } else { searchTerm = new AndTerm(searchTerm, deletedTerm); } } } return searchTerm != null ? folder.search(searchTerm) : folder.getMessages(); }
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/*from w ww. j a v a2s. co 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); } } } }