List of usage examples for javax.mail Folder search
public Message[] search(SearchTerm term) throws MessagingException
From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java
/** * Returns list of unread/read priority {@link GmailMessage} objects * based on the {@code unreadOnly} value * /* w w w . j a v a 2 s . com*/ * @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.googlecode.gmail4j.javamail.ImapGmailClient.java
@Override public GmailMessageList getMessagesBy(EmailSearchStrategy strategy, String value) { SearchTerm seekStrategy = null;/* w w w. j a v a 2 s .c o m*/ switch (strategy) { case SUBJECT: seekStrategy = new SubjectTerm(value); LOG.debug("Fetching emails with a subject of \"" + value + "\""); break; case TO: seekStrategy = new RecipientStringTerm(Message.RecipientType.TO, value); LOG.debug("Fetching emails sent to \"" + value + "\""); break; case FROM: seekStrategy = new FromStringTerm(value); LOG.debug("Fetching emails sent from \"" + value + "\""); break; case CC: seekStrategy = new RecipientStringTerm(Message.RecipientType.CC, value); LOG.debug("Fetching emails CC'd to \"" + value + "\""); break; case DATE_GT: seekStrategy = new SentDateTerm(SentDateTerm.GT, parseDate(value)); LOG.debug("Fetching emails with a send date newer than \"" + value + "\""); break; case DATE_LT: seekStrategy = new SentDateTerm(SentDateTerm.LT, parseDate(value)); LOG.debug("Fetching emails with a send date newer than \"" + value + "\""); break; case DATE_EQ: seekStrategy = new SentDateTerm(SentDateTerm.EQ, parseDate(value)); LOG.debug("Fetching emails with a send date newer than \"" + value + "\""); break; case KEYWORD: seekStrategy = new BodyTerm(value); LOG.debug("Fetching emails containing the keyword \"" + value + "\""); break; case UNREAD: seekStrategy = new FlagTerm(new Flags(Flags.Flag.SEEN), false); LOG.debug("Fetching all unread emails"); break; } try { final GmailMessageList found = new GmailMessageList(); final Store store = openGmailStore(); final Folder folder = getFolder(this.srcFolder, store); folder.open(Folder.READ_ONLY); for (final Message msg : folder.search(seekStrategy)) { found.add(new JavaMailGmailMessage(msg)); } LOG.debug("Found " + found.size() + " emails"); return found; } catch (final Exception e) { throw new GmailException("Failed getting unread messages", e); } }
From source file:com.openkm.util.MailUtils.java
/** * Import messages//from ww w .j a v 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: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. co m 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.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 *///from ww w . j a va 2s . 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.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 w w w .j a v a 2 s . co m*/ 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.seleniumtests.connectors.mails.ImapClient.java
/** * get list of all emails in folder//from w w w.ja v a 2 s. co m * * @param folderName folder to read * @param firstMessageTime date from which we should get messages * @param firstMessageIndex index of the firste message to find * @throws MessagingException * @throws IOException */ @Override public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime) throws MessagingException, IOException { if (folderName == null) { throw new MessagingException("folder ne doit pas tre vide"); } // Get folder Folder folder = store.getFolder(folderName); folder.open(Folder.READ_ONLY); // Get directory Message[] messages = folder.getMessages(); List<Message> preFilteredMessages = new ArrayList<>(); final LocalDateTime firstTime = firstMessageTime; // on filtre les message en fonction du mode de recherche if (searchMode == SearchMode.BY_INDEX || firstTime == null) { for (int i = firstMessageIndex, n = messages.length; i < n; i++) { preFilteredMessages.add(messages[i]); } } else { preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() { private static final long serialVersionUID = 1L; @Override public boolean match(Message msg) { try { return !msg.getReceivedDate() .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant())); } catch (MessagingException e) { return false; } } })); } List<Email> filteredEmails = new ArrayList<>(); lastMessageIndex = messages.length; for (Message message : preFilteredMessages) { String contentType = ""; try { contentType = message.getContentType(); } catch (MessagingException e) { MimeMessage msg = (MimeMessage) message; message = new MimeMessage(msg); contentType = message.getContentType(); } // decode content String messageContent = ""; List<String> attachments = new ArrayList<>(); if (contentType.toLowerCase().contains("text/html")) { messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString()); } else if (contentType.toLowerCase().contains("multipart/")) { List<BodyPart> partList = getMessageParts((Multipart) message.getContent()); // store content in list for (BodyPart part : partList) { String partContentType = part.getContentType().toLowerCase(); if (partContentType.contains("text/html")) { messageContent = messageContent .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString())); } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) { messageContent = messageContent.concat((String) part.getContent().toString()); } else if (partContentType.contains("image") || partContentType.contains("application/") || partContentType.contains("text/x-vcard")) { if (part.getFileName() != null) { attachments.add(part.getFileName()); } else { attachments.add(part.getDescription()); } } else { logger.debug("type: " + part.getContentType()); } } } // create a new email filteredEmails.add(new Email(message.getSubject(), messageContent, "", message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(), attachments)); } folder.close(false); return filteredEmails; }
From source file:com.robin.utilities.Utilities.java
/** * A utility that waits for a gmail mailbox to receive a new message with * according to a given SearchTerm. Only "Not seen" messages are searched, * and all match is set as SEEN, but just the first occurrence of the * matching message is returned.//from ww w . j av a 2 s . c o m * @param username the mailbox owner's user name (no @gmail.com required). * @param pass the user password protecting this mailbox * @param st the SearchTerm built to filter messages * @param timeoutMessage the message to show when no such mail found within * timeout * @param timeout The maximum amount of time to wait in milliseconds. * @return a last from the new messages thats match the st conditions */ public EMail waitForMailWithSearchTerm(final String username, final String pass, final SearchTerm st, final String timeoutMessage, final long timeout) { String host = "imap.gmail.com"; final long retryTime = 1000; Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); props.put("mail.imaps.ssl.trust", "*"); EMail email = null; Session session = Session.getDefaultInstance(props, null); try { Store store = session.getStore("imaps"); store.connect(host, username, pass); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_WRITE); FluentWait<Folder> waitForMail = new FluentWait<Folder>(inbox) .withTimeout(timeout, TimeUnit.MILLISECONDS).pollingEvery(retryTime, TimeUnit.MILLISECONDS) .withMessage(timeoutMessage); email = waitForMail.until(new Function<Folder, EMail>() { @Override public EMail apply(final Folder inbox) { EMail email = null; FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); SearchTerm sst = new AndTerm(ft, st); try { inbox.getMessageCount(); Message[] messages = inbox.search(sst); for (Message message : messages) { message.setFlag(Flag.SEEN, true); } if (messages.length > 0) { return new EMail(messages[0]); } } catch (MessagingException e) { Assert.fail(e.getMessage()); } return email; } }); inbox.close(false); store.close(); } catch (MessagingException e) { Assert.fail(e.getMessage()); } return email; }
From source file:com.sonicle.webtop.mail.MailAccount.java
public void deleteByHeaderValue(String header, String value) throws MessagingException { FolderCache fc = getFolderCache(getFolderDrafts()); fc.open();//from w w w. ja v a2 s . c o m Folder folder = fc.getFolder(); Message[] oldmsgs = folder.search(new HeaderTerm(header, value)); if (oldmsgs != null && oldmsgs.length > 0) { for (Message m : oldmsgs) m.setFlag(Flags.Flag.DELETED, true); folder.expunge(); } }
From source file:nl.ordina.bag.etl.mail.loader.IMAPMutatiesFileLoader.java
@Override public void processMessages() { try {//from w ww . j a v a2 s . co 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); } }