List of usage examples for javax.mail.search FlagTerm FlagTerm
public FlagTerm(Flags flags, boolean set)
From source file:com.intranet.intr.inbox.EmpControllerInbox.java
@RequestMapping(value = "/EajaxtestNoL", method = RequestMethod.GET) public @ResponseBody String ajaxtestNoL(Principal principal) { String name = principal.getName(); String result = ""; try {/*from w w w .j a v a2 s.c om*/ users u = usuarioService.getByLogin(name); Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna()); System.out.println("ola" + store); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); Calendar fecha3 = Calendar.getInstance(); fecha3.roll(Calendar.MONTH, false); Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime())); //Message msg[] = inbox.search(ft); System.out.println("MAILS: " + msg.length); for (Message message : msg) { try { /*System.out.println("DATE: "+message.getSentDate().toString()); System.out.println("FROM: "+message.getFrom()[0].toString()); System.out.println("SUBJECT: "+message.getSubject().toString()); System.out.println("CONTENT: "+message.getContent().toString()); System.out.println("******************************************"); */result = result + "<li>" + "<a href='#' class='clearfix'>" + "<span class='msg-body'>" + "<span class='msg-title'>" + "<span class='blue'>" + message.getFrom()[0].toString() + "</span>" + message.getSubject().toString() + "</span>" + "</span>" + "</a>" + "</li> "; } catch (Exception e) { // TODO Auto-generated catch block System.out.println("No Information"); } } } catch (Exception ex) { } return result; }
From source file:com.intranet.intr.inbox.SupControllerInbox.java
@RequestMapping(value = "/ajaxtestNoL", method = RequestMethod.GET) public @ResponseBody String ajaxtestNoL(Principal principal) { String name = principal.getName(); String result = ""; try {/*from ww w . ja v a 2 s . com*/ users u = usuarioService.getByLogin(name); Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna()); System.out.println("ola" + store); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); Calendar fecha3 = Calendar.getInstance(); fecha3.roll(Calendar.MONTH, false); Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime())); //Message msg[] = inbox.search(ft); System.out.println("MAILS: " + msg.length); for (Message message : msg) { try { /*System.out.println("DATE: "+message.getSentDate().toString()); System.out.println("FROM: "+message.getFrom()[0].toString()); System.out.println("SUBJECT: "+message.getSubject().toString()); System.out.println("CONTENT: "+message.getContent().toString()); System.out.println("******************************************"); */result = result + "<li>" + "<a href='#' class='clearfix'>" + "<span class='msg-body'>" + "<span class='msg-title'>" + "<span class='blue'>" + message.getFrom()[0].toString() + "</span>" + message.getSubject().toString() + "</span>" + "</span>" + "</a>" + "</li> "; } catch (Exception e) { // TODO Auto-generated catch block System.out.println("No Information"); } } } catch (Exception ex) { } return result; }
From source file:com.stimulus.archiva.incoming.IAPRunnable.java
public boolean pollMessages() { logger.debug("iap pollmessages() {mailboxworker='" + getName() + "'}"); boolean complete = true; try {//from w ww. j av a 2 s . c om Message[] messages; if (Compare.equalsIgnoreCase(connection.getProtocol().toString(), "IMAP") && connection.getUnread()) { messages = inboxFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } else { messages = inboxFolder.getMessages(); } logger.debug("iap archivemesssages() called"); int noMessages = archiveMessages(messages); if (noMessages < messages.length) { complete = false; } logger.debug("iap archivemesssages() end"); } catch (IndexOutOfBoundsException iobe) { logger.error("mail server start and end message numbers are out of range {serverName='" + connection.getServerName() + "',port='" + connection.getPort() + "',userName='" + connection.getUsername() + "'}"); testOutput("mail server start and end message numbers are out of range"); } catch (Throwable t) { logger.error("failed to retrieve messages during polling operation:" + t.getMessage(), t); testOutput("failed to retrieve messages during polling operation:" + t.getMessage()); } if (testCallback != null) { // we're just testing testOutput("retrieved messages from inbox"); testOutput("test successful"); shutdown = true; } return complete; }
From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java
/** * Mark all {@link GmailMessage}(s) as read in a folder. * * @throws GmailException if unable to mark all {@link GmailMessage} as read *//* w ww.j av a2 s. com*/ public void markAllAsRead() { Folder folder = null; try { final Store store = openGmailStore(); folder = getFolder(this.srcFolder, store); folder.open(Folder.READ_WRITE); for (final Message message : folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false))) { message.setFlag(Flags.Flag.SEEN, true); } } catch (Exception e) { throw new GmailException("ImapGmailClient failed marking" + " all GmailMessage as read", e); } finally { closeFolder(folder); } }
From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java
/** * Returns list of unread/read priority {@link GmailMessage} objects * based on the {@code unreadOnly} value * /*from ww w .java 2 s . co m*/ * @param unreadOnly {@code true} to unread priority {@link GmailMessage} * objects only, {@code false} to read priority {@link GmailMessage} * objects only * @return List of unread/read priority messages * @throws GmailException if unable to get unread/read priority messages */ public List<GmailMessage> getPriorityMessages(boolean unreadOnly) { try { final List<GmailMessage> priorityMessages = new ArrayList<GmailMessage>(); final Store store = openGmailStore(); Folder folder = getFolder(ImapGmailLabel.IMPORTANT.getName(), store); folder.open(Folder.READ_ONLY); for (final Message msg : folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), !unreadOnly))) { priorityMessages.add(new JavaMailGmailMessage(msg)); } return priorityMessages; } catch (final Exception e) { throw new GmailException("Failed getting priority messages", e); } }
From source file:com.ikon.util.MailUtils.java
/** * Import messages/*w w w .ja v a2s . com*/ * http://www.jguru.com/faq/view.jsp?EID=26898 * * == Using Unique Identifier (UIDL) == * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email, * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't * receive it; otherwise receive it. * * == Different property of UIDL in POP3 and IMAP4 == * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is * no longer exist on the POP3 server. * * == Remarks == * You should create different local uidl list for different email account, because the uidl is only * unique for the same account. */ public static String importMessages(String token, MailAccount ma) throws PathNotFoundException, ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException, DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException { log.debug("importMessages({}, {})", new Object[] { token, ma }); Session session = Session.getDefaultInstance(getProperties()); String exceptionMessage = null; try { // Open connection Store store = session.getStore(ma.getMailProtocol()); store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword()); Folder folder = store.getFolder(ma.getMailFolder()); folder.open(Folder.READ_WRITE); Message messages[] = null; if (folder instanceof IMAPFolder) { // IMAP folder UIDs begins at 1 and are supposed to be sequential. // Each folder has its own UIDs sequence, not is a global one. messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID); } else { messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; log.info(i + ": " + msg.getFrom()[0] + " " + msg.getSubject() + " " + msg.getContentType()); log.info("Received: " + msg.getReceivedDate()); log.info("Sent: " + msg.getSentDate()); log.debug("{} -> {} - {}", new Object[] { i, msg.getSubject(), msg.getReceivedDate() }); com.ikon.bean.Mail mail = messageToMail(msg); if (ma.getMailFilters().isEmpty()) { log.debug("Import in compatibility mode"); String mailPath = getUserMailPath(ma.getUser()); importMail(token, mailPath, true, folder, msg, ma, mail); } else { for (MailFilter mf : ma.getMailFilters()) { log.debug("MailFilter: {}", mf); if (checkRules(mail, mf.getFilterRules())) { String mailPath = mf.getPath(); importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail); } } } // Set message as seen if (ma.isMailMarkSeen()) { msg.setFlag(Flags.Flag.SEEN, true); } else { msg.setFlag(Flags.Flag.SEEN, false); } // Delete read mail if requested if (ma.isMailMarkDeleted()) { msg.setFlag(Flags.Flag.DELETED, true); } // Set lastUid if (folder instanceof IMAPFolder) { long msgUid = ((IMAPFolder) folder).getUID(msg); log.info("Message UID: {}", msgUid); ma.setMailLastUid(msgUid); MailAccountDAO.update(ma); } } // Close connection log.debug("Expunge: {}", ma.isMailMarkDeleted()); folder.close(ma.isMailMarkDeleted()); store.close(); } catch (NoSuchProviderException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (MessagingException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (IOException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } log.debug("importMessages: {}", exceptionMessage); return exceptionMessage; }
From source file:com.openkm.util.MailUtils.java
/** * Import messages/* w w w . jav a 2 s .c om*/ * http://www.jguru.com/faq/view.jsp?EID=26898 * * == Using Unique Identifier (UIDL) == * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email, * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't * receive it; otherwise receive it. * * == Different property of UIDL in POP3 and IMAP4 == * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is * no longer exist on the POP3 server. * * == Remarks == * You should create different local uidl list for different email account, because the uidl is only * unique for the same account. */ public static String importMessages(String token, MailAccount ma) throws PathNotFoundException, ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException, DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException { log.debug("importMessages({}, {})", new Object[] { token, ma }); Session session = Session.getDefaultInstance(getProperties()); String exceptionMessage = null; try { // Open connection Store store = session.getStore(ma.getMailProtocol()); store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword()); Folder folder = store.getFolder(ma.getMailFolder()); folder.open(Folder.READ_WRITE); Message messages[] = null; if (folder instanceof IMAPFolder) { // IMAP folder UIDs begins at 1 and are supposed to be sequential. // Each folder has its own UIDs sequence, not is a global one. messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID); } else { messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; log.info("======= ======= {} ======= =======", i); log.info("Subject: {}", msg.getSubject()); log.info("From: {}", msg.getFrom()); log.info("Received: {}", msg.getReceivedDate()); log.info("Sent: {}", msg.getSentDate()); com.openkm.bean.Mail mail = messageToMail(msg); if (ma.getMailFilters().isEmpty()) { log.debug("Import in compatibility mode"); String mailPath = getUserMailPath(ma.getUser()); importMail(token, mailPath, true, folder, msg, ma, mail); } else { for (MailFilter mf : ma.getMailFilters()) { log.debug("MailFilter: {}", mf); if (checkRules(mail, mf.getFilterRules())) { String mailPath = mf.getPath(); importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail); } } } // Set message as seen if (ma.isMailMarkSeen()) { msg.setFlag(Flags.Flag.SEEN, true); } else { msg.setFlag(Flags.Flag.SEEN, false); } // Delete read mail if requested if (ma.isMailMarkDeleted()) { msg.setFlag(Flags.Flag.DELETED, true); } // Set lastUid if (folder instanceof IMAPFolder) { long msgUid = ((IMAPFolder) folder).getUID(msg); log.info("Message UID: {}", msgUid); ma.setMailLastUid(msgUid); MailAccountDAO.update(ma); } } // Close connection log.debug("Expunge: {}", ma.isMailMarkDeleted()); folder.close(ma.isMailMarkDeleted()); store.close(); } catch (NoSuchProviderException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (MessagingException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (IOException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } log.debug("importMessages: {}", exceptionMessage); return exceptionMessage; }
From source file:nl.ordina.bag.etl.mail.loader.IMAPMutatiesFileLoader.java
@Override public void processMessages() { try {//from w ww.j av a2 s . c o m Session session = Session.getDefaultInstance(new Properties(), null); Store store = session.getStore(protocol); if (port == 0) store.connect(host, username, password); else store.connect(host, port, username, password); Folder folder = store.getFolder(folderName); if (folder == null) throw new RuntimeException("Folder " + folderName + " not found!"); folder.open(Folder.READ_WRITE); try { FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); Message messages[] = folder.search(ft); for (Message message : messages) { messageHandler.handle(message); message.setFlags(new Flags(Flags.Flag.SEEN), true); } } finally { folder.close(true); store.close(); } } catch (MessagingException | IOException | JAXBException e) { throw new ProcessingException(e); } }
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;/*w w w .ja v a 2s .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.apache.camel.component.mail.MailConsumer.java
protected int poll() throws Exception { // must reset for each poll shutdownRunningTask = null;/*from w ww . ja va2 s .c om*/ pendingExchanges = 0; int polledMessages = 0; ensureIsConnected(); if (store == null || folder == null) { throw new IllegalStateException("MailConsumer did not connect properly to the MailStore: " + getEndpoint().getConfiguration().getMailStoreLogInformation()); } if (LOG.isDebugEnabled()) { LOG.debug("Polling mailfolder: " + getEndpoint().getConfiguration().getMailStoreLogInformation()); } if (getEndpoint().getConfiguration().getFetchSize() == 0) { LOG.warn( "Fetch size is 0 meaning the configuration is set to poll no new messages at all. Camel will skip this poll."); return 0; } // ensure folder is open if (!folder.isOpen()) { folder.open(Folder.READ_WRITE); } try { int count = folder.getMessageCount(); if (count > 0) { Message[] messages; // should we process all messages or only unseen messages if (getEndpoint().getConfiguration().isUnseen()) { messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } else { messages = folder.getMessages(); } polledMessages = processBatch(CastUtils.cast(createExchanges(messages))); } else if (count == -1) { throw new MessagingException("Folder: " + folder.getFullName() + " is closed"); } } catch (Exception e) { handleException(e); } finally { // need to ensure we release resources try { if (folder.isOpen()) { folder.close(true); } } catch (Exception e) { // some mail servers will lock the folder so we ignore in this case (CAMEL-1263) LOG.debug("Could not close mailbox folder: " + folder.getName(), e); } } return polledMessages; }