Java Code Examples for javax.mail.Store#getFolder()

The following examples show how to use javax.mail.Store#getFolder() . 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 6 votes vote down vote up
/**
 * Check whether email received by reading the emails.
 *
 * @param protocol to connect to the store
 * @param user     whose mail store should be connected
 * @param subject  the subject of the mail to search
 * @return
 * @throws MessagingException when unable to connect to the store
 */
public static boolean isMailReceived(String protocol, GreenMailUser user, String subject)
        throws MessagingException {
    Store store = getConnection(user, protocol);
    Folder folder = store.getFolder(EMAIL_INBOX);
    folder.open(Folder.READ_ONLY);
    boolean isReceived = false;
    Message[] messages = folder.getMessages();
    for (Message message : messages) {
        if (message.getSubject().contains(subject)) {
            log.info("Found the Email with Subject : " + subject);
            isReceived = true;
            break;
        }
    }
    return isReceived;
}
 
Example 2
Source File: ImapSubjectLineTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
private void testSubject(String subject) throws Exception {
    GreenMailUser user = greenMail.setUser("to1@localhost", "pwd");
    assertNotNull(greenMail.getImap());

    MailFolder folder = greenMail.getManagers().getImapHostManager().getFolder(user, "INBOX");
    storeSearchTestMessages(greenMail.getImap().createSession(), folder, subject);

    greenMail.waitForIncomingEmail(1);

    final Store store = greenMail.getImap().createStore();
    store.connect("to1@localhost", "pwd");
    try {
        Folder imapFolder = store.getFolder("INBOX");
        imapFolder.open(Folder.READ_ONLY);

        Message[] imapMessages = imapFolder.getMessages();
        assertTrue(null != imapMessages && imapMessages.length == 1);
        Message imapMessage = imapMessages[0];
        assertEquals(subject.replaceAll("\\s+",""), imapMessage.getSubject().replaceAll("\\s+",""));
    } finally {
        store.close();
    }
}
 
Example 3
Source File: AbstractIMAPRiverUnitTest.java    From elasticsearch-imap with Apache License 2.0 6 votes vote down vote up
protected void deleteMailsFromUserMailbox(final Properties props, final String folderName, final int start, final int deleteCount,
        final String user, final String password) throws MessagingException {
    final Store store = Session.getInstance(props).getStore();

    store.connect(user, password);
    checkStoreForTestConnection(store);
    final Folder f = store.getFolder(folderName);
    f.open(Folder.READ_WRITE);

    final int msgCount = f.getMessageCount();

    final Message[] m = deleteCount == -1 ? f.getMessages() : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1));
    int d = 0;

    for (final Message message : m) {
        message.setFlag(Flag.DELETED, true);
        logger.info("Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject());
        d++;
    }

    f.close(true);
    logger.info("Deleted " + d + " messages");
    store.close();

}
 
Example 4
Source File: GreenMailServer.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Delete all emails in the inbox.
 *
 * @param protocol protocol used to connect to the server
 * @throws MessagingException if we're unable to connect to the store
 */
public static void deleteAllEmails(String protocol, GreenMailUser user) throws MessagingException {
    Folder inbox = null;
    Store store = getConnection(user, protocol);
    try {
        inbox = store.getFolder(EMAIL_INBOX);
        inbox.open(Folder.READ_WRITE);
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            message.setFlag(Flags.Flag.DELETED, true);
            log.info("Deleted email Subject : " + message.getSubject());
        }
    } finally {
        if (inbox != null) {
            inbox.close(true);
        }
        if (store != null) {
            store.close();
        }
    }
}
 
Example 5
Source File: EMailTestServer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public List<EMailMessageModel> getEmailsInFolder(String user, String password, String folderName) throws Exception {
    if (server instanceof SmtpServer) {
        throw new Exception("SMTP not applicable for reading folders");
    }

    Store store = server.createStore();
    store.connect(user, password);

    Folder newFolder = store.getFolder(folderName);
    if (! newFolder.exists()) {
        throw new Exception("No folder with name " + folderName);
    }

    newFolder.open(Folder.READ_ONLY);
    List<EMailMessageModel> models = new ArrayList<>();
    for (Message msg : newFolder.getMessages()) {
        models.add(createMessageModel(msg));
    }

    return models;
}
 
Example 6
Source File: EmailUtil.java    From product-es with Apache License 2.0 6 votes vote down vote up
/**
 * This method delete all the sent mails. Can be used after a particular test class
 *
 * @throws  MessagingException
 * @throws  IOException
 */
public static void deleteSentMails() throws MessagingException, IOException {
    Properties props = new Properties();
    props.load(new FileInputStream(new File(
            TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator
                    + "smtp.properties")));
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString());

    Folder sentMail = store.getFolder("[Gmail]/Sent Mail");
    sentMail.open(Folder.READ_WRITE);
    Message[] messages =sentMail.getMessages();
    Flags deleted = new Flags(Flags.Flag.DELETED);
    sentMail.setFlags(messages,deleted,true);
    sentMail.close(true);
    store.close();
}
 
Example 7
Source File: MailReceiverUtils.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * delete all mails in the test mailbox, exceptions that may be produced during working with test
 * mailbox:
 *
 * @throws MessagingException
 */
public void cleanMailBox() throws MessagingException {
  Properties properties = System.getProperties(); // Get system properties
  Session session = Session.getDefaultInstance(properties); // Get the default Session object.
  Store store =
      session.getStore("imaps"); // Get a Store object that implements the specified protocol.
  store.connect(
      host, user,
      password); // Connect to the current host using the specified username and password.
  Folder folder =
      store.getFolder("inbox"); // Create a Folder object corresponding to the given name.
  folder.open(Folder.READ_WRITE); // Open the Folder.
  Message[] messages = folder.getMessages();
  for (int i = 0, n = messages.length; i < n; i++) {
    messages[i].setFlag(Flags.Flag.DELETED, true);
  }
  closeStoreAndFolder(folder, store);
}
 
Example 8
Source File: EmailUtil.java    From product-es with Apache License 2.0 6 votes vote down vote up
/**
 * This method delete all the sent mails. Can be used after a particular test class
 *
 * @throws  MessagingException
 * @throws  IOException
 */
public static void deleteSentMails() throws MessagingException, IOException {
    Properties props = new Properties();
    props.load(new FileInputStream(new File(
            TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator
                    + "smtp.properties")));
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString());

    Folder sentMail = store.getFolder("[Gmail]/Sent Mail");
    sentMail.open(Folder.READ_WRITE);
    Message[] messages =sentMail.getMessages();
    Flags deleted = new Flags(Flags.Flag.DELETED);
    sentMail.setFlags(messages,deleted,true);
    sentMail.close(true);
    store.close();
}
 
Example 9
Source File: SMTPTestCase.java    From javamail-mock2 with Apache License 2.0 6 votes vote down vote up
@Test
public void test3SendMessage() throws Exception {

    Session.getDefaultInstance(getProperties());

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test 1");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    Transport.send(msg);

    final Store store = session.getStore("mock_pop3");
    store.connect("[email protected]", null);
    final Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    Assert.assertEquals(1, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));
    Assert.assertEquals("Test 1", inbox.getMessage(1).getSubject());
    inbox.close(false);

}
 
Example 10
Source File: StoreMail.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception {

		// 创建一个有具体连接信息的Properties对象
		Properties prop = new Properties();
		prop.setProperty("mail.debug", "true");
		prop.setProperty("mail.store.protocol", "pop3");
		prop.setProperty("mail.pop3.host", MAIL_SERVER_HOST);

		// 1、创建session
		Session session = Session.getInstance(prop);

		// 2、通过session得到Store对象
		Store store = session.getStore();

		// 3、连上邮件服务器
		store.connect(MAIL_SERVER_HOST, USER, PASSWORD);

		// 4、获得邮箱内的邮件夹
		Folder folder = store.getFolder("inbox");
		folder.open(Folder.READ_ONLY);

		// 获得邮件夹Folder内的所有邮件Message对象
		Message[] messages = folder.getMessages();
		for (int i = 0; i < messages.length; i++) {
			String subject = messages[i].getSubject();
			String from = (messages[i].getFrom()[0]).toString();
			System.out.println("第 " + (i + 1) + "封邮件的主题:" + subject);
			System.out.println("第 " + (i + 1) + "封邮件的发件人地址:" + from);
		}

		// 5、关闭
		folder.close(false);
		store.close();
	}
 
Example 11
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 12
Source File: POP3TestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddMessages() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13

    final Store store = session.getStore();
    store.connect("[email protected]", null);
    final Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    Assert.assertEquals(3, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));

    inbox.close(true);

    Assert.assertEquals(3, inbox.getMessageCount());

    inbox.open(Folder.READ_ONLY);
    inbox.getMessage(1).setFlag(Flag.DELETED, true);

    inbox.close(true);
    inbox.open(Folder.READ_ONLY);
    Assert.assertEquals(2, inbox.getMessageCount());
    Assert.assertTrue(inbox instanceof POP3Folder);
    Assert.assertEquals("12", ((POP3Folder) inbox).getUID(inbox.getMessage(1)));
    inbox.close(true);
}
 
Example 13
Source File: DockerServiceIT.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllServices() throws MessagingException, InterruptedException {
    // Ugly workaround : GreenMail in docker starts with open TCP connections,
    //                   but TLS sockets might not be ready yet.
    TimeUnit.SECONDS.sleep(1);

    // Send messages via SMTP and secure SMTPS
    GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost",
            "test1", "Test GreenMail Docker service",
            ServerSetupTest.SMTP.createCopy(bindAddress));
    GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost",
            "test2", "Test GreenMail Docker service",
            ServerSetupTest.SMTPS.createCopy(bindAddress));

    // IMAP
    for (ServerSetup setup : Arrays.asList(
            ServerSetupTest.IMAP.createCopy(bindAddress),
            ServerSetupTest.IMAPS.createCopy(bindAddress),
            ServerSetupTest.POP3.createCopy(bindAddress),
            ServerSetupTest.POP3S.createCopy(bindAddress))) {
        final Store store = Session.getInstance(setup.configureJavaMailSessionProperties(null, false)).getStore();
        store.connect("foo@localhost", "foo@localhost");
        try {
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            assertEquals("Can not check mails using "+store.getURLName(), 2, folder.getMessageCount());
        } finally {
            store.close();
        }
    }
}
 
Example 14
Source File: ArdulinkMailOnCamelIntegrationTest.java    From Ardulink-2 with Apache License 2.0 5 votes vote down vote up
private Message retrieveViaImap(String host, int port, String user, String password) throws MessagingException {
	Properties props = new Properties();
	props.setProperty("mail.store.protocol", "imap");
	props.setProperty("mail.imap.port", String.valueOf(port));
	Session session = Session.getInstance(props, null);
	Store store = session.getStore();
	store.connect(host, user, password);
	Folder inbox = store.getFolder("INBOX");
	inbox.open(Folder.READ_ONLY);
	int messageCount = inbox.getMessageCount();
	return messageCount == 0 ? null : inbox.getMessage(1);
}
 
Example 15
Source File: MalinatorUtil.java    From qaf with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

		Properties props = new Properties();

		String host = "pop.mailinator.com";
		String username = "x-test-m";
		String password = "mypwdxxx";
		String provider = "pop3";

		Session session = Session.getDefaultInstance(props, null);
		Store store = session.getStore(provider);
		store.connect(host, username, password);

		Folder inbox = store.getFolder("INBOX");
		if (inbox == null) {
			System.out.println("No INBOX");
			System.exit(1);
		}
		inbox.open(Folder.READ_ONLY);

		Message[] messages = inbox.getMessages();
		for (int i = 0; i < messages.length; i++) {
			System.out.println("Message " + (i + 1));
			messages[i].writeTo(System.out);
		}
		inbox.close(false);
		store.close();

	}
 
Example 16
Source File: AbstractMailExampleTest.java    From wildfly-camel-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void sendEmailTest() throws Exception {
    try {
        deployer.deploy(GREENMAIL_WAR);
        deployer.deploy(getDeploymentName());

        StringBuilder endpointURL = new StringBuilder("from=user1@localhost");
        endpointURL.append("&to=user2@localhost")
                .append("&subject=Greetings")
                .append("&message=Hello");

        HttpRequest.HttpResponse result = HttpRequest.post(getEndpointAddress("send"))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .content(endpointURL.toString())
                .getResponse();

        String responseBody = result.getBody();
        Assert.assertTrue("Sent successful: " + responseBody, responseBody.contains("Message sent successfully"));

        // Verify that the email made it to the target address
        Store store = mailSession.getStore("pop3");
        store.connect();

        Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_WRITE);
        Assert.assertEquals(1, folder.getMessageCount());
    } finally {
        deployer.undeploy(getDeploymentName());
        deployer.undeploy(GREENMAIL_WAR);
    }
}
 
Example 17
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 18
Source File: EmailUtil.java    From product-es with Apache License 2.0 4 votes vote down vote up
/**
 * This method read e-mails from Gmail inbox and find whether the notification of particular type is found.
 *
 * @param   notificationType    Notification types supported by publisher and store.
 * @return  whether email is found for particular type.
 * @throws  Exception
 */
public static boolean readGmailInboxForNotification(String notificationType) throws Exception {
    boolean isNotificationMailAvailable = false;
    long waitTime = 10000;
    Properties props = new Properties();
    props.load(new FileInputStream(new File(
            TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator
                    + "smtp.properties")));
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString());

    Folder inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Thread.sleep(waitTime);

    long startTime = System.currentTimeMillis();
    long endTime = 0;
    int count = 1;
    while (endTime - startTime < 180000 && !isNotificationMailAvailable) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if(!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());

                    if (message.getSubject().contains(notificationType)) {
                        isNotificationMailAvailable = true;

                    }
                    // Optional : deleting the  mail
                    message.setFlag(Flags.Flag.DELETED, true);
                } catch (MessageRemovedException e) {
                    log.error("Could not read the message subject. Message is removed from inbox");
                }
            }

        }
        endTime = System.currentTimeMillis();
        Thread.sleep(waitTime);
        endTime += count*waitTime;
        count++;
    }
    inbox.close(true);
    store.close();
    return isNotificationMailAvailable;
}
 
Example 19
Source File: EmailUtil.java    From product-es with Apache License 2.0 4 votes vote down vote up
/**
 * This method read verification e-mail from Gmail inbox and returns the verification URL.
 *
 * @return  verification redirection URL.
 * @throws  Exception
 */
public static String readGmailInboxForVerification() throws Exception {
    boolean isEmailVerified = false;
    long waitTime = 10000;
    String pointBrowserURL = "";
    Properties props = new Properties();
    props.load(new FileInputStream(new File(
            TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator
                    + "smtp.properties")));
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString());

    Folder inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Thread.sleep(waitTime);
    long startTime = System.currentTimeMillis();
    long endTime = 0;
    int count = 1;
    while (endTime - startTime < 180000 && !isEmailVerified) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if (!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());
                    if (message.getSubject().contains("EmailVerification")) {
                        pointBrowserURL = getBodyFromMessage(message);
                        isEmailVerified = true;
                    }

                    // Optional : deleting the mail
                    message.setFlag(Flags.Flag.DELETED, true);
                } catch (MessageRemovedException e){
                    log.error("Could not read the message subject. Message is removed from inbox");
                }
            }
        }
        endTime = System.currentTimeMillis();
        Thread.sleep(waitTime);
        endTime += count*waitTime;
        count++;
    }
    inbox.close(true);
    store.close();
    return pointBrowserURL;
}
 
Example 20
Source File: ParallelPollingPOPMailSource.java    From elasticsearch-imap with Apache License 2.0 4 votes vote down vote up
private ProcessResult processMessageSlice(final int start, final int end, final String folderName) throws Exception {

        final long startTime = System.currentTimeMillis();
        final Store store = Session.getInstance(props).getStore();
        store.connect(user, password);
        final Folder folder = store.getFolder(folderName);

        IMAPUtils.open(folder);

        try {

            final Message[] msgs = folder.getMessages(start, end);
            folder.fetch(msgs, IMAPUtils.FETCH_PROFILE_HEAD);

            int processedCount = 0;

            for (final Message m : msgs) {
                try {
                    mailDestination.onMessage(m);
                    processedCount++;

                    if (Thread.currentThread().isInterrupted()) {
                        break;
                    }

                } catch (final Exception e) {
                    stateManager.onError("Unable to make indexable message", m, e);
                    logger.error("Unable to make indexable message due to {}", e, e.toString());

                    IMAPUtils.open(folder);
                }
            }

            final long endTime = System.currentTimeMillis() + 1;
            return new ProcessResult(processedCount, endTime - startTime);

        } finally {

            IMAPUtils.close(folder);
            IMAPUtils.close(store);
        }

    }