javax.mail.search.FlagTerm Java Examples

The following examples show how to use javax.mail.search.FlagTerm. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OMailServiceImpl.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
public void fetchMails(OMailSettings settings, String folderName, Consumer<Message> consumer) throws MessagingException {
    Session session = createSession(settings, createCheckMailProperties(settings));
    Store store = session.getStore("imaps");
    store.connect();
    Folder folder = store.getFolder(folderName);
    folder.open(Folder.READ_WRITE);
    Message [] messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
    for (int i = messages.length - 1; i >= 0; i--) {
        Message message = messages[i];
        consumer.accept(message);
        message.setFlag(Flags.Flag.SEEN, true);
    }
    folder.close(false);
    store.close();
}
 
Example #2
Source File: MailSteps.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Valid activation email.
 *
 * @param mailHost
 *            example: imap.gmail.com
 * @param mailUser
 *            login of mail box
 * @param mailPassword
 *            password of mail box
 * @param senderMail
 *            sender of mail box
 * @param subjectMail
 *            subject of mail box
 * @param firstCssQuery
 *            the first matching element
 * @param conditions
 *            list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
 * @throws TechnicalException
 *             is throws if you have a technical error (format, configuration, datas, ...) in NoraUi.
 *             Exception with message and with screenshot and with exception if functional error but no screenshot and no exception if technical error.
 * @throws FailureException
 *             if the scenario encounters a functional error
 */
@Experimental(name = "validActivationEmail")
@RetryOnFailure(attempts = 3, delay = 60)
@Conditioned
@Et("Je valide le mail d'activation {string}(\\?)")
@And("I valid activation email {string}(\\?)")
public void validActivationEmail(String mailHost, String mailUser, String mailPassword, String senderMail, String subjectMail, String firstCssQuery, List<GherkinStepCondition> conditions)
        throws FailureException, TechnicalException {
    try {
        final Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imap");
        final Session session = Session.getDefaultInstance(props, null);
        final Store store = session.getStore("imaps");
        store.connect(mailHost, mailUser, mailPassword);
        final Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        final SearchTerm filterA = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        final SearchTerm filterB = new FromTerm(new InternetAddress(senderMail));
        final SearchTerm filterC = new SubjectTerm(subjectMail);
        final SearchTerm[] filters = { filterA, filterB, filterC };
        final SearchTerm searchTerm = new AndTerm(filters);
        final Message[] messages = inbox.search(searchTerm);
        for (final Message message : messages) {
            validateActivationLink(subjectMail, firstCssQuery, message);
        }
    } catch (final Exception e) {
        new Result.Failure<>("", Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_MAIL_ACTIVATION), subjectMail), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
    }
}
 
Example #3
Source File: PollMailInvocation.java    From camunda-bpm-mail with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #4
Source File: Email.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #5
Source File: SearchTermBuilder.java    From greenmail with Apache License 2.0 5 votes vote down vote up
private static SearchTerm createFlagSearchTerm(String pFlagName, boolean pValue) {
    Flags.Flag flag = toFlag(pFlagName);
    Flags flags = new javax.mail.Flags();
    if (null == flag) { // user flags
        flags.add(pFlagName);
    } else {
        flags.add(flag);
    }
    return new FlagTerm(flags, pValue);
}
 
Example #6
Source File: ImapInboxReader.java    From actframework with Apache License 2.0 5 votes vote down vote up
private String tryReadIn(Folder folder, String email) throws MessagingException, IOException {
    folder.open(Folder.READ_WRITE);
    try {
        Flags seen = new Flags(Flags.Flag.SEEN);
        FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
        Message messages[] = folder.search(unseenFlagTerm);
        if (0 == messages.length) {
            return null;
        }
        for (Message message : messages) {
            if (message.isExpunged()) {
                continue;
            }
            Address[] addresses = message.getAllRecipients();
            for (Address address : addresses) {
                if (address.toString().contains(email)) {
                    String type = message.getContentType();
                    if (type.startsWith("text")) {
                        String s = message.getContent().toString();
                        message.setFlag(Flags.Flag.SEEN, true);
                        return s;
                    } else {
                        E.unsupport("Unsupported content type: " + type);
                    }
                }
            }
        }
        return null;
    } finally {
        folder.close(false);
    }
}
 
Example #7
Source File: MailsShouldBeWellReceived.java    From james-project with Apache License 2.0 4 votes vote down vote up
static Message[] searchForAll(Folder inbox) throws MessagingException {
    return inbox.search(new FlagTerm(new Flags(), false));
}
 
Example #8
Source File: MailConnection.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public void setFlagTermNotDraft() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.DRAFT ), false ) );
}
 
Example #9
Source File: MailConnection.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public void setFlagTermDraft() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.DRAFT ), true ) );
}
 
Example #10
Source File: MailConnection.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public void setFlagTermNotFlagged() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.FLAGGED ), false ) );
}
 
Example #11
Source File: MailConnection.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public void setFlagTermFlagged() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.FLAGGED ), true ) );
}
 
Example #12
Source File: MailConnection.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public void setFlagTermUnread() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.SEEN ), false ) );
}
 
Example #13
Source File: MailConnection.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public void setFlagTermRead() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.SEEN ), true ) );
}
 
Example #14
Source File: MailConnection.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public void setFlagTermOld() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.RECENT ), false ) );
}
 
Example #15
Source File: MailConnection.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public void setFlagTermNew() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.RECENT ), true ) );
}
 
Example #16
Source File: MailAccountServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public int fetchEmails(EmailAccount mailAccount, boolean unseenOnly)
    throws MessagingException, IOException {

  if (mailAccount == null) {
    return 0;
  }

  log.debug(
      "Fetching emails from host: {}, port: {}, login: {} ",
      mailAccount.getHost(),
      mailAccount.getPort(),
      mailAccount.getLogin());

  com.axelor.mail.MailAccount account = null;
  if (mailAccount.getServerTypeSelect().equals(EmailAccountRepository.SERVER_TYPE_IMAP)) {
    account =
        new ImapAccount(
            mailAccount.getHost(),
            mailAccount.getPort().toString(),
            mailAccount.getLogin(),
            mailAccount.getPassword(),
            getSecurity(mailAccount));
  } else {
    account =
        new Pop3Account(
            mailAccount.getHost(),
            mailAccount.getPort().toString(),
            mailAccount.getLogin(),
            mailAccount.getPassword(),
            getSecurity(mailAccount));
  }

  MailReader reader = new MailReader(account);
  final Store store = reader.getStore();
  final Folder inbox = store.getFolder("INBOX");

  // open as READ_WRITE to mark messages as seen
  inbox.open(Folder.READ_WRITE);

  // find all unseen messages
  final FetchProfile profile = new FetchProfile();
  javax.mail.Message[] messages;
  if (unseenOnly) {
    final FlagTerm unseen = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
    messages = inbox.search(unseen);
  } else {
    messages = inbox.getMessages();
  }

  profile.add(FetchProfile.Item.ENVELOPE);

  // actually fetch the messages
  inbox.fetch(messages, profile);
  log.debug("Total emails unseen: {}", messages.length);

  int count = 0;
  for (javax.mail.Message message : messages) {
    if (message instanceof MimeMessage) {
      MailParser parser = new MailParser((MimeMessage) message);
      parser.parse();
      createMessage(mailAccount, parser, message.getSentDate());
      count++;
    }
  }

  log.debug("Total emails fetched: {}", count);

  return count;
}
 
Example #17
Source File: MailConnection.java    From hop with Apache License 2.0 4 votes vote down vote up
public void setFlagTermNew() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.RECENT ), true ) );
}
 
Example #18
Source File: Email.java    From BotLibre with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 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);
	}
}
 
Example #19
Source File: JavaMailContainer.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example #20
Source File: MailConnection.java    From hop with Apache License 2.0 4 votes vote down vote up
public void setFlagTermNotDraft() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.DRAFT ), false ) );
}
 
Example #21
Source File: MailConnection.java    From hop with Apache License 2.0 4 votes vote down vote up
public void setFlagTermDraft() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.DRAFT ), true ) );
}
 
Example #22
Source File: MailConnection.java    From hop with Apache License 2.0 4 votes vote down vote up
public void setFlagTermNotFlagged() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.FLAGGED ), false ) );
}
 
Example #23
Source File: MailConnection.java    From hop with Apache License 2.0 4 votes vote down vote up
public void setFlagTermFlagged() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.FLAGGED ), true ) );
}
 
Example #24
Source File: MailConnection.java    From hop with Apache License 2.0 4 votes vote down vote up
public void setFlagTermUnread() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.SEEN ), false ) );
}
 
Example #25
Source File: MailConnection.java    From hop with Apache License 2.0 4 votes vote down vote up
public void setFlagTermRead() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.SEEN ), true ) );
}
 
Example #26
Source File: MailConnection.java    From hop with Apache License 2.0 4 votes vote down vote up
public void setFlagTermOld() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.RECENT ), false ) );
}