Java Code Examples for javax.mail.search.FlagTerm

The following examples show how to use javax.mail.search.FlagTerm. These examples are extracted from open source projects. 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 Project: Orienteer   Source File: OMailServiceImpl.java    License: 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 Project: NoraUi   Source File: MailSteps.java    License: 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 Project: camunda-bpm-mail   Source File: PollMailInvocation.java    License: 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 Project: BotLibre   Source File: Email.java    License: 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 Project: actframework   Source File: ImapInboxReader.java    License: 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 6
Source Project: greenmail   Source File: SearchTermBuilder.java    License: 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 7
Source Project: hop   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermNew() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.RECENT ), true ) );
}
 
Example 8
Source Project: hop   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermOld() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.RECENT ), false ) );
}
 
Example 9
Source Project: hop   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermRead() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.SEEN ), true ) );
}
 
Example 10
Source Project: hop   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermUnread() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.SEEN ), false ) );
}
 
Example 11
Source Project: hop   Source File: MailConnection.java    License: 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 Project: hop   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermNotFlagged() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.FLAGGED ), false ) );
}
 
Example 13
Source Project: hop   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermDraft() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.DRAFT ), true ) );
}
 
Example 14
Source Project: hop   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermNotDraft() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.DRAFT ), false ) );
}
 
Example 15
Source Project: scipio-erp   Source File: JavaMailContainer.java    License: 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 16
Source Project: BotLibre   Source File: Email.java    License: 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 17
Source Project: james-project   Source File: MailsShouldBeWellReceived.java    License: 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 18
@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 19
Source Project: pentaho-kettle   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermNew() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.RECENT ), true ) );
}
 
Example 20
Source Project: pentaho-kettle   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermOld() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.RECENT ), false ) );
}
 
Example 21
Source Project: pentaho-kettle   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermRead() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.SEEN ), true ) );
}
 
Example 22
Source Project: pentaho-kettle   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermUnread() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.SEEN ), false ) );
}
 
Example 23
Source Project: pentaho-kettle   Source File: MailConnection.java    License: 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 Project: pentaho-kettle   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermNotFlagged() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.FLAGGED ), false ) );
}
 
Example 25
Source Project: pentaho-kettle   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermDraft() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.DRAFT ), true ) );
}
 
Example 26
Source Project: pentaho-kettle   Source File: MailConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void setFlagTermNotDraft() {
  addSearchTerm( new FlagTerm( new Flags( Flags.Flag.DRAFT ), false ) );
}