@Override public synchronized void fetchMails() { if(folders.get(inboxName).isOpen()){ try { messages = folders.get(inboxName).search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); folders.get(inboxName).fetch(messages, fetchProfile); // flag as seen folders.get(inboxName).setFlags(messages, new Flags(Flags.Flag.SEEN), true); } catch (Exception e) { e.printStackTrace(); } }else { logger.info("Inbox not open, trying to reconnect..."); connectToServer(); if(folders.get(inboxName).isOpen()){ logger.info("Reconnect successful, fetching mails"); fetchMails(); }else{ logger.error("Reconnect failed, inbox still not open."); } } }
/** * Check the inbox for new messages, and process each message. */ public void checkEmail() { try { log("Checking email.", Level.INFO); Store store = connectStore(); Folder inbox = store.getFolder("INBOX"); if (inbox == null) { throw new BotException("Failed to check email, no INBOX."); } inbox.open(Folder.READ_WRITE); Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); inbox.setFlags(messages, new Flags(Flags.Flag.SEEN), true); //Message[] messages = inbox.getMessages(); if ((messages != null) && (messages.length > 0)) { log("Processing emails", Level.INFO, messages.length); Network memory = getBot().memory().newMemory(); Vertex sense = memory.createVertex(getPrimitive()); Vertex vertex = sense.getRelationship(Primitive.LASTMESSAGE); long lastMessage = 0; if (vertex != null) { lastMessage = ((Number)vertex.getData()).longValue(); } long maxMessage = 0; int count = 0; // Increase script timeout. Language language = getBot().mind().getThought(Language.class); int timeout = language.getMaxStateProcess(); language.setMaxStateProcess(timeout * 2); try { for (int index = 0; index < messages.length; index++) { if (index > (this.maxEmails * 2)) { log("Max old email limit reached", Level.WARNING, this.maxEmails * 2); break; } long recievedTime = 0; if (messages[index].getReceivedDate() == null) { log("Missing received date", Level.FINE, messages[index].getSubject()); recievedTime = messages[index].getSentDate().getTime(); } else { recievedTime = messages[index].getReceivedDate().getTime(); } if ((System.currentTimeMillis() - recievedTime) > DAY) { log("Day old email", Level.INFO, messages[index].getSubject()); continue; } if (recievedTime > lastMessage) { count++; if (count > this.maxEmails) { log("Max email limit reached", Level.WARNING, this.maxEmails); break; } input(messages[index]); Utils.sleep(100); if (recievedTime > maxMessage) { maxMessage = recievedTime; } } } if (maxMessage != 0) { sense.setRelationship(Primitive.LASTMESSAGE, memory.createVertex(maxMessage)); memory.save(); } } finally { language.setMaxStateProcess(timeout); } } log("Done checking email.", Level.INFO); inbox.close(false); store.close(); } catch (MessagingException exception) { log(exception); } }
/** * Return a list in inbox message headers. */ public List<String> getInbox() { List<String> emails = new ArrayList<String>(); Store store = null; Folder inbox = null; try { store = connectStore(); inbox = store.getFolder("INBOX"); if (inbox == null) { log(new BotException("Failed to access inbox, no INBOX.")); } inbox.open(Folder.READ_ONLY); Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); //Message[] messages = inbox.getMessages(1, Math.min(inbox.getMessageCount(), 50)); for (int index = 0; index < 10 && index < messages.length; index++) { emails.add(0, messages[index].getReceivedDate() + " - " + String.valueOf(getFrom(messages[index])) + ": " + messages[index].getSubject()); } inbox.close(false); store.close(); } catch (MessagingException exception) { log(new BotException("Failed to access email: " + exception.getMessage(), exception)); } finally { try { if (inbox != null) { inbox.close(false); } if (store != null) { store.close(); } } catch (Exception ignore) {} } return emails; }
protected void checkMessages(Store store, Session session) throws MessagingException { if (!store.isConnected()) { store.connect(); } // open the default folder Folder folder = store.getDefaultFolder(); if (!folder.exists()) { throw new MessagingException("No default (root) folder available"); } // open the inbox folder = folder.getFolder(INBOX); if (!folder.exists()) { throw new MessagingException("No INBOX folder available"); } // get the message count; stop if nothing to do folder.open(Folder.READ_WRITE); int totalMessages = folder.getMessageCount(); if (totalMessages == 0) { folder.close(false); return; } // get all messages Message[] messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); FetchProfile profile = new FetchProfile(); profile.add(FetchProfile.Item.ENVELOPE); profile.add(FetchProfile.Item.FLAGS); profile.add("X-Mailer"); folder.fetch(messages, profile); // process each message for (Message message: messages) { // process each un-read message if (!message.isSet(Flags.Flag.SEEN)) { long messageSize = message.getSize(); if (message instanceof MimeMessage && messageSize >= maxSize) { Debug.logWarning("Message from: " + message.getFrom()[0] + "not received, too big, size:" + messageSize + " cannot be more than " + maxSize + " bytes", module); // set the message as read so it doesn't continue to try to process; but don't delete it message.setFlag(Flags.Flag.SEEN, true); } else { this.processMessage(message, session); if (Debug.verboseOn()) Debug.logVerbose("Message from " + UtilMisc.toListArray(message.getFrom()) + " with subject [" + message.getSubject() + "] has been processed." , module); message.setFlag(Flags.Flag.SEEN, true); if (Debug.verboseOn()) Debug.logVerbose("Message [" + message.getSubject() + "] is marked seen", module); // delete the message after processing if (deleteMail) { if (Debug.verboseOn()) Debug.logVerbose("Message [" + message.getSubject() + "] is being deleted", module); message.setFlag(Flags.Flag.DELETED, true); } } } } // expunge and close the folder folder.close(true); }
public synchronized static boolean doActionGmail(MessageProcess f, int attempts) { try { Properties props = System.getProperties(); props.setProperty("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("smtp.gmail.com", DefaultUserConf.EMAIL, DefaultUserConf.PASSWORD); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_WRITE); // Get directory Flags seen = new Flags(Flags.Flag.SEEN); FlagTerm unseenFlagTerm = new FlagTerm(seen, false); Message messages[] = inbox.search(unseenFlagTerm); for (int i = 0; i < messages.length; i++) { f.treatMessage(messages[i]); } // Close connection inbox.close(true); store.close(); return true; } catch (Exception e) { Logger.traceERROR(e); Logger.traceERROR("Attempts : " + attempts + " / " + MAX_ATTEMPS); if (attempts > MAX_ATTEMPS) { return false; } else { doActionGmail(f, attempts++); } } return false; }
public synchronized static boolean doActionAEI(MessageProcess f, int attempts) { try { Properties props = new Properties(); props.put("mail.smtp.host", "ssl0.ovh.net"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( "philippe.remy%junior-aei.com", "phremy"); } }); Store store = session.getStore("imap"); store.connect("ssl0.ovh.net", "philippe.remy%junior-aei.com", "phremy"); // Get folder Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); // Get directory Flags seen = new Flags(Flags.Flag.SEEN); FlagTerm unseenFlagTerm = new FlagTerm(seen, false); Message messages[] = inbox.search(unseenFlagTerm); for (int i = 0; i < messages.length; i++) { f.treatMessage(messages[i]); } // Close connection inbox.close(true); store.close(); return true; } catch (Exception e) { Logger.traceERROR(e); Logger.traceERROR("Attempts : " + attempts + " / " + MAX_ATTEMPS); if (attempts > MAX_ATTEMPS) { return false; } else { doActionAEI(f, attempts++); } } return false; }
private MessageListResult getFlagChangesOfMessages(TreeSet<MessageListElement> loadedMessages) throws MessagingException { List<MessageListElement> emails = new LinkedList<MessageListElement>(); Store store = getStore(account); if (store == null || !store.isConnected()) { return new MessageListResult(emails, MessageListResult.ResultType.ERROR); } IMAPFolder imapFolder = (IMAPFolder)store.getFolder(accountFolder.folder); imapFolder.open(Folder.READ_ONLY); UIDFolder uidFolder = imapFolder; long smallestUID = getSmallestUID(loadedMessages); Message messages[] = imapFolder.getMessagesByUID(smallestUID, UIDFolder.LASTUID); FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); Message unseenMsgs[] = imapFolder.search(ft, messages); addMessagesToListAs(uidFolder, emails, unseenMsgs, loadedMessages, false); // searching for seen messages List<Message> seenMessages = new ArrayList<Message>(Arrays.asList(messages)); for (int k = 0; k < unseenMsgs.length; k++) { String unseenUid = Long.toString(uidFolder.getUID(unseenMsgs[k])); for (int l = 0; l < seenMessages.size(); ) { String seenUid = Long.toString(uidFolder.getUID(seenMessages.get(l))); if (seenUid.equals(unseenUid)) { seenMessages.remove(l); } else { l++; } } } addMessagesToListAs(uidFolder, emails, seenMessages.toArray(new Message[seenMessages.size()]), loadedMessages, true); imapFolder.close(false); return new MessageListResult(emails, MessageListResult.ResultType.FLAG_CHANGE); }
public List<Mail> getNewEmails(MailCredentials credentials) throws MessagingException, IOException { Properties properties = getServerProperties(credentials.getProtocol(), credentials.getHost(), "" + credentials.getPort()); Session session = Session.getDefaultInstance(properties); // connects to the message store Store store = session.getStore(credentials.getProtocol()); store.connect(credentials.getUsername(), credentials.getPassword()); logger.debug("url:" + store.getURLName()); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_ONLY); logger.debug("unread:" + folderInbox.getUnreadMessageCount() + ", new:" + folderInbox.getNewMessageCount()); // fetches new messages from server FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); Message messages[] = folderInbox.search(ft); List<Mail> mails = getMails(messages); // disconnect folderInbox.close(false); store.close(); return Lists.reverse(mails); }
@Override public Object invokeTarget() throws Exception { // poll only messages which are not deleted Message[] messages = target.search(new FlagTerm(new Flags(Flag.DELETED), false)); return Arrays.asList(messages); }
/** * Returns a <pre>{@link SearchTerm}</pre> to be used when retrieving messages. * Default term is only for unseen emails, but when retrieveSeenEmails is * set to true it returns a union of terms for both unseen and seen messages. * * @return a search term to be used for message retrieval. */ private SearchTerm getSearchTerm() { Flags seenFlag = new Flags(Flag.SEEN); FlagTerm unseenFlagTerm = new FlagTerm(seenFlag, false); if (retrieveSeenEmails) { FlagTerm seenFlagTerm = new FlagTerm(seenFlag, true); return new OrTerm(unseenFlagTerm, seenFlagTerm); } return unseenFlagTerm; }
public synchronized Message[] search(SearchTerm paramSearchTerm) throws MessagingException { if (paramSearchTerm instanceof FlagTerm) { FlagTerm flagTerm = (FlagTerm) paramSearchTerm; Flags flags = flagTerm.getFlags(); if (flags.equals(new Flags(Flags.Flag.SEEN))) { try { return getUnreadMessage(0); } catch (Exception e) { throw new MessagingException(e.getMessage(),e); } } } throw new MessagingException("Ews folder don't support search with search term " + paramSearchTerm); }
public void run() { try { Properties props = new Properties(); //props.put("mail.debug", "true"); Session session = Session.getInstance(props); int port = Integer.parseInt(worker.getParams().get("port")); String storeType = port == 993 ? "imaps" : "imap"; Store store = session.getStore(storeType); logger.info("Request " + worker.getParams().get("host")); store.connect(worker.getParams().get("host"), port, worker.getParams().get("username"), worker.getParams().get("password")); Folder inbox; if(worker.getParams().get("folder") == null || worker.getParams().get("folder").isEmpty()) { inbox = store.getFolder("Inbox"); } else { inbox = store.getFolder(worker.getParams().get("folder")); } inbox.open(Folder.READ_ONLY); javax.mail.Message[] messages; if(worker.getLastRequest() != null) { messages = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, worker.getLastRequest())); } else { messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } for(int i = 0; i < messages.length; i++) { String mid = messages[i].getHeader("Message-ID").toString(); if(mid == null || mid.isEmpty()) { mid = "urn:" + worker.getParams().get("host") + ":" + messages[i].getMessageNumber(); } Address[] addresses = messages[i].getFrom(); StringBuilder from = new StringBuilder(); StringBuilder producer = new StringBuilder(); if(addresses != null && addresses.length >= 1) { from.append(addresses[0].toString()); for(int j = 0; j < addresses.length; j++) { producer.append(addresses[j].toString()); } } Message message = new Message(); message.setMid(mid); message.setUrl("mailto://" + from.toString()); message.setMessage(messages[i].getSubject()); message.setDate(messages[i].getReceivedDate()); message.setProducer(producer.toString()); queue.push(this, message); } inbox.close(false); store.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } }
/** * Populate all the search criterions in searchCriterion map */ private void initSearchCriterions() { searchCriterion = new EnumMap<SearchCriterion, FlagTerm>( SearchCriterion.class); Flags seen = new Flags(Flags.Flag.SEEN); FlagTerm unseenFlagTerm = new FlagTerm(seen, false); searchCriterion.put(SearchCriterion.UNREAD, unseenFlagTerm); }
public SearchTermBuilder unseen(Op op) { SearchTerm st = new FlagTerm(new Flags(Flags.Flag.SEEN), false); addTerm(op, st); return this; }
public SearchTermBuilder flag(Op op, Flags flags, boolean set) { SearchTerm st = new FlagTerm(flags, set); addTerm(op, st); return this; }
public synchronized static Message[] readAll(String protocol, String server, int securityConnection, int port, String user, String password, boolean onlyUnreadMessages) { Message[] msgs = null; try { Properties props = System.getProperties(); updateSecurityProps(protocol, server, securityConnection, props); Session session = Session.getDefaultInstance(props, null); if (LOGGER.isDebugEnabled()) { session.setDebug(true); } else { session.setDebug(false); } // instantiate POP3-store and connect to server store = session.getStore(protocol); boolean connected = SyncStore.connect(store, protocol, server, port, user, password); if (!connected) { return msgs; } connPoint = SyncStore.getConnPoint(store, protocol, server, port, user, password); store = connPoint.getStore(); // access default folder folder = store.getDefaultFolder(); // can't find default folder if (folder == null) { throw new Exception("No default folder"); } // messages are always in folder INBOX folder = folder.getFolder("INBOX"); // can't find INBOX if (folder == null) { throw new Exception("No POP3 INBOX"); } // open folder folder.open(Folder.READ_WRITE); // retrieve messages if (onlyUnreadMessages) { FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); msgs = folder.search(ft); } else { msgs = folder.getMessages(); } } catch (Exception ex) { if (LogThrottle.isReady("MailReader1",240)) { LOGGER.error(ExceptionUtils.getStackTrace(ex)); } } return msgs; }
public void setFlagTermNew() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.RECENT), true)); }
public void setFlagTermOld() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.RECENT), false)); }
public void setFlagTermRead() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.SEEN), true)); }
public void setFlagTermUnread() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); }
public void setFlagTermFlagged() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.FLAGGED), true)); }
public void setFlagTermNotFlagged() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.FLAGGED), false)); }
public void setFlagTermDraft() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.DRAFT), true)); }
public void setFlagTermNotDraft() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.DRAFT), false)); }