Java Code Examples for javax.mail.Folder#search()

The following examples show how to use javax.mail.Folder#search() . 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: GreenMailServer.java    From micro-integrator with Apache License 2.0 9 votes vote down vote up
/**
 * Check mail folder for an email using subject.
 *
 * @param emailSubject Email subject
 * @param folder       mail folder to check for an email
 * @param protocol     protocol used to connect to the server
 * @return whether mail received or not
 * @throws MessagingException if we're unable to connect to the store
 */
private static boolean isMailReceivedBySubject(String emailSubject, String folder, String protocol,
                                               GreenMailUser user) throws MessagingException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection(user, protocol);
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the Email with Subject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
    } finally {
        if (store != null) {
            store.close();
        }
    }
    return emailReceived;
}
 
Example 2
Source File: GreenMailServer.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Check mail folder for an email using subject.
 *
 * @param emailSubject Email subject
 * @param folder       mail folder to check for an email
 * @param protocol     protocol used to connect to the server
 * @return whether mail received or not
 * @throws MessagingException if we're unable to connect to the store
 */
private static boolean isMailReceivedBySubject(String emailSubject, String folder, String protocol,
        GreenMailUser user) throws MessagingException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection(user, protocol);
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the Email with Subject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
    } finally {
        if (store != null) {
            store.close();
        }
    }
    return emailReceived;
}
 
Example 3
Source File: MailToTransportUtil.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Check a particular email has received to a given email folder by email subject.
 *
 * @param emailSubject - Email emailSubject to find email is in inbox or not
 * @return - found the email or not
 * @throws ESBMailTransportIntegrationTestException - Is thrown if an error occurred while reading the emails
 */
public static boolean isMailReceivedBySubject(String emailSubject, String folder)
        throws ESBMailTransportIntegrationTestException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection();
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the email emailSubject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
        return emailReceived;
    } catch (MessagingException ex) {
        log.error("Error when getting mail count ", ex);
        throw new ESBMailTransportIntegrationTestException("Error when getting mail count ", ex);
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                log.warn("Error when closing the store ", e);
            }
        }
    }
}
 
Example 4
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 5
Source File: MailToTransportUtil.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Check a particular email has received to a given email folder by email subject.
 *
 * @param emailSubject - Email emailSubject to find email is in inbox or not
 * @return - found the email or not
 * @throws ESBMailTransportIntegrationTestException - Is thrown if an error occurred while reading the emails
 */
public static boolean isMailReceivedBySubject(String emailSubject, String folder)
        throws ESBMailTransportIntegrationTestException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection();
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the email emailSubject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
        return emailReceived;
    } catch (MessagingException ex) {
        log.error("Error when getting mail count ", ex);
        throw new ESBMailTransportIntegrationTestException("Error when getting mail count ", ex);
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                log.warn("Error when closing the store ", e);
            }
        }
    }
}
 
Example 6
Source File: PortalTester.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the latest email with the given subject from the email inbox.
 * 
 * @param subject
 *            the email subject
 * @return the email body or null if no email was found
 * @throws Exception
 */
public String readLatestEmailWithSubject(String subject) throws Exception {
    Store store = mailSession.getStore();
    store.connect();

    Folder folder = store.getFolder(MAIL_INBOX);
    folder.open(Folder.READ_WRITE);

    Message[] messages = null;

    messages = folder.search(new SubjectTerm(subject));

    String body = null;
    if (messages.length > 0) {
        Message latest = messages[0];

        for (Message m : messages) {
            if (latest.getSentDate().compareTo(m.getSentDate()) < 0) {
                latest = m;
            }
        }
        body = (String) latest.getContent();
    }

    folder.close(false);
    store.close();

    return body;
}
 
Example 7
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 8
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 9
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 10
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 11
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 12
Source File: DeleteMailConnector.java    From camunda-bpm-mail with Apache License 2.0 3 votes vote down vote up
protected Message[] getMessagesByIds(Folder folder, List<String> messageIds) throws MessagingException {

    List<MessageIDTerm> idTerms = messageIds.stream()
        .map(MessageIDTerm::new)
        .collect(Collectors.toList());

    OrTerm searchTerm = new OrTerm(idTerms.toArray(new MessageIDTerm[idTerms.size()]));

    return folder.search(searchTerm);
  }