javax.mail.Store Java Examples

The following examples show how to use javax.mail.Store. 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 7 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 #2
Source File: MessageParser.java    From OA with GNU General Public License v3.0 6 votes vote down vote up
public static void parse(Message... messages) {
	if (messages == null || messages.length == 0) {
		System.out.println("没有任何邮件");
	} else {
		for (Message m : messages) {
			parse(m);
		}
		// 最后关闭连接
		if (messages[0] != null) {
			Folder folder = messages[0].getFolder();
			if (folder != null) {
				try {
					Store store = folder.getStore();
					folder.close(false);// 参数false表示对邮件的修改不传送到服务器上
					if (store != null) {
						store.close();
					}
				} catch (MessagingException e) {
					// ignore
				}
			}
		}
	}

}
 
Example #3
Source File: StoreCrawler.java    From mnIMAPSync with Apache License 2.0 6 votes vote down vote up
/**
 * Static method to populate a {@link Index} with the messages in an {@link Store}
 */
public static Index populateFromStore(final Index index, Store store, int threads)
    throws MessagingException, InterruptedException {

  MessagingException messagingException = null;
  final ExecutorService service = Executors.newFixedThreadPool(threads);
  try {
    index.setFolderSeparator(String.valueOf(store.getDefaultFolder().getSeparator()));
    crawlFolders(store, index, store.getDefaultFolder(), service);
  } catch (MessagingException ex) {
    messagingException = ex;
  }
  service.shutdown();
  service.awaitTermination(1, TimeUnit.HOURS);
  if (index.hasCrawlException()) {
    messagingException = index.getCrawlExceptions().iterator().next();
  }
  if (messagingException != null) {
    throw messagingException;
  }
  return index;
}
 
Example #4
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 #5
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Close connection
 * <b>Note</b>Internal method
 * @throws MessagingException
 */
public void closeStoreConnection(
                                  boolean storeConnected ) throws MessagingException {

    if (storeConnected) {
        // the folder is empty when the message is not loaded from IMAP server, but from a file
        Folder imapFolder = message.getFolder();
        if (imapFolder == null) {
            imapFolder = partOfImapFolder; // in case of nested package but still originating from IMAP server
        }
        if (imapFolder != null) {
            Store store = imapFolder.getStore();
            if (store != null && store.isConnected()) {
                // closing store closes and its folders
                log.debug("Closing store (" + store.toString() + ") and associated folders");
                store.close();
            }
        }
    }
}
 
Example #6
Source File: ImapFolder.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
ImapFolder( Store store,
            String serverHost,
            String folderName,
            String userName,
            String password ) {

    this.isOpen = false;
    this.store = store;
    this.serverHost = serverHost;
    this.folderName = folderName;
    this.userName = userName;
    this.password = password;

    newMetaDataList = new ArrayList<MetaData>();
    allMetaDataList = new ArrayList<MetaData>();
}
 
Example #7
Source File: EMailTestServer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public int getEmailCountInFolder(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);
    return newFolder.getMessageCount();
}
 
Example #8
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 #9
Source File: EmailUtils.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 * Connects to email server with credentials provided to read from a given folder of the email application
 *
 * @param username    Email username (e.g. [email protected])
 * @param password    Email password
 * @param server      Email server (e.g. smtp.email.com)
 * @param emailFolder Folder in email application to interact with
 */
public EmailUtils(String username, String password, String server, EmailFolder emailFolder)
        throws MessagingException {

    Properties props = System.getProperties();

    try {
        props.load(new FileInputStream(new File("../src/test/resources/email.properties")));
    } catch (Exception e) {
        logger.error("Error occured while reading email properties ", e);
        System.exit(-1);
    }

    Session session = Session.getInstance(props);
    Store store = session.getStore("imaps");
    store.connect(server, username, password);

    folder = store.getFolder(emailFolder.getText());
    folder.open(Folder.READ_WRITE);
}
 
Example #10
Source File: GreenMailServer.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Get the connection to a mail store
 *
 * @param user     whose mail store should be connected
 * @param protocol protocol used to connect
 * @return
 * @throws MessagingException when unable to connect to the store
 */
private static Store getConnection(GreenMailUser user, String protocol) throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getInstance(props);
    int port;
    if (PROTOCOL_POP3.equals(protocol)) {
        port = 3110;
    } else if (PROTOCOL_IMAP.equals(protocol)) {
        port = 3143;
    } else {
        port = 3025;
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", "localhost");
        props.put("mail.smtp.port", "3025");
    }
    URLName urlName = new URLName(protocol, BIND_ADDRESS, port, null, user.getLogin(), user.getPassword());
    Store store = session.getStore(urlName);
    store.connect();
    return store;
}
 
Example #11
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 #12
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 #13
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 #14
Source File: Email.java    From smslib-v3 with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<OutboundMessage> getMessagesToSend() throws Exception
{
	List<OutboundMessage> retValue = new ArrayList<OutboundMessage>();
	Store s = this.mailSession.getStore();
	s.connect();
	Folder inbox = s.getFolder(getProperty("mailbox_name", "INBOX"));
	inbox.open(Folder.READ_WRITE);
	for (Message m : inbox.getMessages())
	{
		OutboundMessage om = new OutboundMessage(m.getSubject(), m.getContent().toString());
		om.setFrom(m.getFrom().toString());
		om.setDate(m.getReceivedDate());
		retValue.add(om);
		// Delete message from inbox
		m.setFlag(Flags.Flag.DELETED, true);
	}
	inbox.close(true);
	s.close();
	return retValue;
}
 
Example #15
Source File: ThunderbirdMailbox.java    From mail-importer with Apache License 2.0 6 votes vote down vote up
public JavaxMailStorage get() throws MessagingException {
  Properties properties = new Properties();
  properties.setProperty("mail.store.protocol", "mstor");
  properties.setProperty("mstor.mbox.metadataStrategy", "none");
  properties.setProperty("mstor.mbox.cacheBuffers", "disabled");
  properties.setProperty("mstor.mbox.bufferStrategy", "mapped");
  properties.setProperty("mstor.metadata", "disabled");
  properties.setProperty("mstor.mozillaCompatibility", "enabled");

  Session session = Session.getDefaultInstance(properties);

  // /Users/flan/Desktop/Copy of Marie's Mail/Mail/Mail/mail.lean.to
  File mailbox = new File(commandLineArguments.mailboxFileName);
  if (!mailbox.exists()) {
    throw new MessagingException("No such mailbox:" + mailbox);
  }

  Store store = session.getStore(
      new URLName("mstor:" + mailbox.getAbsolutePath()));
  store.connect();

  return new ThunderbirdMailStorage(
      logger,
      new JavaxMailFolder(store.getDefaultFolder()),
      statusParser);
}
 
Example #16
Source File: Email.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public Store connectStore() throws MessagingException {
	initProperties();
	if (isSSLRequired()) {
		return connectStoreSSL();
	}
	Properties properties = new Properties();
	properties.put("mail." + getProtocol() + ".timeout", TIMEOUT);
	properties.put("mail." + getProtocol() + ".connectiontimeout", TIMEOUT);
	//properties.setProperty("mail.store.protocol", getProtocol());
	Session session = Session.getInstance(properties, null);
	Store store = session.getStore(getProtocol());
	if (getIncomingPort() == 0) {
		store.connect(getIncomingHost(), getUsername(), getPassword());
	} else {
		store.connect(getIncomingHost(), getIncomingPort(), getUsername(), getPassword());
	}
	return store;
}
 
Example #17
Source File: Email.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Connect and verify the email settings.
 */
public void connect() {
	Store store = null;
	try {
		log("Connecting email.", Level.FINER);
		store = connectStore();
		connectSession();
		log("Done connecting email.", Level.FINER);
	} catch (MessagingException messagingException) {
		BotException exception = new BotException("Failed to connect - " + messagingException.getMessage(), messagingException);
		log(exception);
		throw exception;
	} finally {
		try {
			if (store != null) {
				store.close();
			}
		} catch (Exception ignore) {}
	}
}
 
Example #18
Source File: GreenMailServer.java    From product-ei 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 #19
Source File: SMTPTestCase.java    From javamail-mock2 with Apache License 2.0 6 votes vote down vote up
@Test
public void test2SendMessage2() throws Exception {

    final Transport transport = session.getTransport(Providers.getSMTPProvider("makes_no_difference_here", true, true));

    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.sendMessage(msg, new Address[] { new InternetAddress("[email protected]") });

    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 #20
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 #21
Source File: MxPopTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
private void retrieveMail() throws NoSuchProviderException,
        MessagingException, IOException {
    Properties properties = new Properties();
    Session session = Session.getInstance(properties);
    Store store =
            session.getStore(new URLName("pop3://john:secret@localhost:"
                    + PORT_POP + "/INBOX"));
    store.connect();
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    Message[] messages = folder.getMessages();
    assertEquals(1, messages.length);
    Message message = messages[0];
    assertEquals("Hello World!\r\n", message.getContent());
    message.setFlag(Flags.Flag.DELETED, true);
    folder.close(true);
    store.close();
}
 
Example #22
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 #23
Source File: cfPOP3.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private Store openConnection( cfSession _Session ) throws cfmRunTimeException	{
	String server	 = getDynamic( _Session, "SERVER" ).getString();
	boolean secure = getSecure( _Session );
	int	port			 = getPort( _Session, secure );
	String user    = getDynamic( _Session, "USERNAME" ).getString();
	String pass    = getDynamic( _Session, "PASSWORD" ).getString();
	
	Properties props = new Properties();
	String protocol = "pop3";
	if ( secure ){
		protocol = "pop3s";
	}
	
	props.put( "mail.transport.protocol", protocol );
	props.put( "mail." + protocol + ".port", String.valueOf( port ) );
	
	// This is the fix for bug NA#3156
 	    props.put("mail.mime.address.strict", "false");
	
	// With WebLogic Server 8.1sp4 and an IMAIL server, we're seeing that sometimes the first
	// attempt to connect after messages have been deleted fails with either a MessagingException 
	// of "Connection reset" or an AuthenticationFailedException of "EOF on socket".  To work
	// around this let's try 3 attempts to connect before giving up.
	for ( int numAttempts = 1; numAttempts < 4; numAttempts++ )
	{
		try{
			Session session 	= Session.getInstance( props );
			Store mailStore		= session.getStore( protocol );
			mailStore.connect( server, user, pass );
			return mailStore;
		}catch(Exception E){
			if ( numAttempts == 3 )
				throw newRunTimeException( E.getMessage() );
		}
	}
	
	// The code in the for loop should either return or throw an exception
	// so this code should never get hit.
	return null;
}
 
Example #24
Source File: LiveChatBean.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public Store connectStore() throws MessagingException {
	Properties properties = new Properties();
	properties.put("mail." + this.instance.getEmailProtocol() + ".timeout", 5000);
	properties.put("mail." + this.instance.getEmailProtocol() + ".connectiontimeout", 5000);
	//properties.setProperty("mail.store.protocol", getProtocol());
    Session session = Session.getInstance(properties, null);
    Store store = session.getStore(this.instance.getEmailProtocol());
    if (this.instance.getEmailIncomingPort() == 0) {
    	store.connect(this.instance.getEmailIncomingHost(), this.instance.getEmailUserName(), this.instance.getEmailPassword());
    } else {
    	store.connect(this.instance.getEmailIncomingHost(), this.instance.getEmailIncomingPort(), this.instance.getEmailUserName(), this.instance.getEmailPassword());
    }
    return store;
}
 
Example #25
Source File: LiveChatBean.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public void sendEmail(final String address, final String subject, final String text,  final String html) {
	Store store = null;
	try {
		Stats.stats.emails++;
		AdminDatabase.instance().log(Level.INFO, "Sending email", address, subject);
        //store = connectStore();
		Session session = connectSession();

		MimeMessage message = new MimeMessage(session);
	    message.setFrom(new InternetAddress(this.instance.getEmailAddress()));
	    message.addRecipient(Message.RecipientType.TO, new InternetAddress(address));
	    message.setSubject(subject);
	    if (html != null) {
		    message.setContent(html, "text/html; charset=UTF-8");
	    } else {
	    	message.setText(text);
	    }

	    // Send message
	    Transport.send(message);
	} catch (Throwable messagingException) {
		AdminDatabase.instance().log(messagingException);
		error(messagingException);
	} finally {
		try {
			if (store != null) {
				store.close();
			}
		} catch (Exception ignore) {}
	}
}
 
Example #26
Source File: MailConnectionTest.java    From hop with Apache License 2.0 5 votes vote down vote up
public Mconn( ILogChannel log ) throws HopException, MessagingException {
  super( log, MailConnectionMeta.PROTOCOL_IMAP, "junit", 0, "junit", "junit", false, false, "junit" );

  store = Mockito.mock( Store.class );

  inbox = Mockito.mock( Folder.class );
  a = Mockito.mock( Folder.class );
  b = Mockito.mock( Folder.class );
  c = Mockito.mock( Folder.class );

  when( a.getFullName() ).thenReturn( "A" );
  when( b.getFullName() ).thenReturn( "B" );
  when( c.getFullName() ).thenReturn( "C" );

  when( a.exists() ).thenReturn( true );
  when( b.exists() ).thenReturn( true );
  when( c.exists() ).thenReturn( cCreated );
  when( c.create( Mockito.anyInt() ) ).thenAnswer( new Answer<Boolean>() {
    @Override
    public Boolean answer( InvocationOnMock invocation ) throws Throwable {
      Object arg0 = invocation.getArguments()[ 0 ];
      mode = Integer.class.cast( arg0 );
      cCreated = true;
      return true;
    }
  } );

  when( inbox.getFolder( "a" ) ).thenReturn( a );
  when( a.getFolder( "b" ) ).thenReturn( b );
  when( b.getFolder( "c" ) ).thenReturn( c );

  when( store.getDefaultFolder() ).thenReturn( inbox );

}
 
Example #27
Source File: cfPOP3.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private Folder openFolder( cfSession _Session, Store popStore )  throws cfmRunTimeException	{
	try{
		Folder folder = popStore.getDefaultFolder();
		Folder popFolder = folder.getFolder("INBOX");
		popFolder.open( Folder.READ_WRITE );
		return popFolder;
	}catch(Exception E){
		throw newRunTimeException( E.getMessage() );
	}
}
 
Example #28
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 #29
Source File: POP3TestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test(expected = MockTestException.class)
public void testOnlyInbox() 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
    mb.getRoot().getOrAddSubFolder("test").create().add(msg);

    final Store store = session.getStore(Providers.getPOP3Provider("makes_no_differernce", false, true));
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();

    try {
        defaultFolder.getFolder("test");
    } catch (final MessagingException e) {
        throw new MockTestException(e);
    }

}
 
Example #30
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;
}