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

The following examples show how to use javax.mail.Folder#getMessageCount() . 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: BatchFolderIterator.java    From hop with Apache License 2.0 6 votes vote down vote up
public BatchFolderIterator( Folder folder, Integer batchSize, Integer start, Integer end ) {
  this.folder = folder;
  try {
    this.msgCount = folder.getMessageCount();
  } catch ( MessagingException e ) {
    this.msgCount = SIZE_ERR;
  }
  this.batchSize = ( batchSize == null ) ? msgCount : batchSize;

  this.start = ( start == null ) ? 1 : start;
  this.end = ( end == null ) ? msgCount : end;

  this.batchFirst = this.start;
  this.batchLast = this.start - 1;

  messages = new Message[ 0 ];
  // if (!getNextBatch() || msgCount == SIZE_ERR) throw new RuntimeException("TODO:"); //TODO

}
 
Example 2
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 3
Source File: MailListener.java    From Ardulink-1 with Apache License 2.0 6 votes vote down vote up
private static void clear(Folder folder) throws MessagingException {
	if(folder.exists() && (folder.getType() & Folder.HOLDS_MESSAGES) == Folder.HOLDS_MESSAGES) {
		int totMessages = folder.getMessageCount();
		System.out.println(totMessages + " messages from folder: " + folder.getFullName());
		folder.open(Folder.READ_WRITE);
		Message[] messages = folder.getMessages();
		for (int i = 0; i < messages.length; i++) {
			System.out.println("Deleting message: " + (i+1) + " of " + totMessages);
			messages[i].setFlag(Flags.Flag.DELETED, true);
		}
		folder.close(true);
	}
	Folder[] childs = folder.list();
	for (int i = 0; i < childs.length; i++) {
		clear(childs[i]);
	}
}
 
Example 4
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 5
Source File: BatchFolderIterator.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public BatchFolderIterator( Folder folder, Integer batchSize, Integer start, Integer end ) {
  this.folder = folder;
  try {
    this.msgCount = folder.getMessageCount();
  } catch ( MessagingException e ) {
    this.msgCount = SIZE_ERR;
  }
  this.batchSize = ( batchSize == null ) ? msgCount : batchSize;

  this.start = ( start == null ) ? 1 : start;
  this.end = ( end == null ) ? msgCount : end;

  this.batchFirst = this.start;
  this.batchLast = this.start - 1;

  messages = new Message[0];
  // if (!getNextBatch() || msgCount == SIZE_ERR) throw new RuntimeException("TODO:"); //TODO

}
 
Example 6
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 7
Source File: TableLoaderInbox.java    From hana-native-adapters with Apache License 2.0 5 votes vote down vote up
@Override
protected Object getNextRowData(AdapterRowSet rows) throws AdapterException {
	try {
		Folder inbox = ((IMAPAdapter) getAdapter()).inbox;
		if (getRowNumberToRead() < inbox.getMessageCount()) {
			return inbox.getMessage(getRowNumberToRead()+1);
		} else {
			hasNoMoreRows();
			return null;
		}
	} catch (MessagingException e) {
		throw new AdapterException(e);
	}

}
 
Example 8
Source File: MiscTest.java    From jqm with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmail() throws Exception
{
    // Do not run in Eclipse, as it does not support the SMTP Maven plugin.
    Assume.assumeTrue(!System.getProperty("java.class.path").contains("eclipse"));

    CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar", TestHelpers.qVip, 42,
            "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true, cnx);
    JobRequest.create("MarsuApplication", "TestUser").setEmail("[email protected]").submit();

    addAndStartEngine();
    TestHelpers.waitFor(1, 20000, cnx); // Need time for async mail sending.

    Assert.assertEquals(1, TestHelpers.getOkCount(cnx));
    Assert.assertEquals(0, TestHelpers.getNonOkCount(cnx));

    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imap");
    int nbMail = 0;
    try
    {
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect("localhost", 10143, "testlogin", "testpassword");
        Folder inbox = store.getFolder("INBOX");
        nbMail = inbox.getMessageCount();
    }
    catch (Exception mex)
    {
        mex.printStackTrace();
    }
    Assert.assertEquals(1, nbMail);
}
 
Example 9
Source File: StoreCrawler.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
private static void crawlFolders(Store store, Index index, Folder folder,
    ExecutorService service) throws MessagingException {
  if (folder != null) {
    final String folderName = folder.getFullName();
    index.addFolder(folderName);
    if ((folder.getType() & Folder.HOLDS_MESSAGES) == Folder.HOLDS_MESSAGES) {
      folder.open(Folder.READ_ONLY);
      if (folder.getMode() != Folder.READ_ONLY) {
        folder.expunge();
      }
      final int messageCount = folder.getMessageCount();
      folder.close(false);
      int pos = 1;
      while (pos + MNIMAPSync.BATCH_SIZE <= messageCount) {
        service.execute(new FolderCrawler(store, folderName, pos,
            pos + MNIMAPSync.BATCH_SIZE, index));
        pos = pos + MNIMAPSync.BATCH_SIZE;
      }
      service.execute(new FolderCrawler(store, folderName, pos, messageCount, index));
    }
    //Folder recursion. Get all children
    if ((folder.getType() & Folder.HOLDS_FOLDERS) == Folder.HOLDS_FOLDERS) {
      for (Folder child : folder.list()) {
        crawlFolders(store, index, child, service);
      }
    }
  }
}
 
Example 10
Source File: StoreDeleter.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
private void deleteTargetMessages(Folder targetFolder) throws MessagingException {
    if (targetFolder != null) {
        final String targetFolderName = targetFolder.getFullName();
        final String sourceFolderName = targetToSourceFolderName(targetFolderName, sourceIndex, targetIndex);
        if ((targetFolder.getType() & Folder.HOLDS_MESSAGES) == Folder.HOLDS_MESSAGES) {
            targetFolder.open(Folder.READ_WRITE);
            if (targetFolder.getMode() != Folder.READ_ONLY) {
                targetFolder.expunge();
            }
            final int messageCount = targetFolder.getMessageCount();
            targetFolder.close(false);
            int pos = 1;
            while (pos + MNIMAPSync.BATCH_SIZE <= messageCount) {
                service.execute(
                        new MessageDeleter(this, targetFolderName, pos,
                                pos + MNIMAPSync.BATCH_SIZE, false, sourceIndex.
                                getFolderMessages(sourceFolderName)));
                pos = pos + MNIMAPSync.BATCH_SIZE;
            }
            service.execute(new MessageDeleter(this, targetFolderName,
                    pos, messageCount, true, sourceIndex.getFolderMessages(sourceFolderName)));
        }
        //Folder recursion. Get all children
        if ((targetFolder.getType() & Folder.HOLDS_FOLDERS) == Folder.HOLDS_FOLDERS) {
            for (Folder child : targetFolder.list()) {
                deleteTargetMessages(child);
            }
        }
    }
}
 
Example 11
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 12
Source File: DefaultReceiveEmailProvider.java    From xframium-java with GNU General Public License v3.0 4 votes vote down vote up
public MessageWrapper _getEmail( String hostName, MessageFilter[] messageFilters, Map<String, String> propertyMap )
{
    Properties mailProps = new Properties();
    mailProps.putAll( propertyMap );

    List<Message> messageList = new ArrayList<Message>( 10 );
    MessageWrapper messageWrapper = null;

    try
    {
        Session emailSession = Session.getDefaultInstance( mailProps );
        Store store = emailSession.getStore( propertyMap.get( PROTOCOL ) );
        store.connect( hostName, propertyMap.get( USER_NAME ), propertyMap.get( PASSWORD ) );

        Folder emailFolder = store.getFolder( propertyMap.get( FOLDER_NAME ) != null ? propertyMap.get( FOLDER_NAME ) : DEFAULT_FOLDER_NAME );
        emailFolder.open( Folder.READ_WRITE );

        Message[] messages = emailFolder.getMessages();

        int messageCount = emailFolder.getMessageCount();
        if ( messageCount > MAX_MESSAGES )
            messageCount = MAX_MESSAGES;

        if ( log.isInfoEnabled() )
            log.info( "Processing " + messageCount + " messages" );

        for ( int i = 0; i < messageCount; i++ )
        {
            if ( applyFilters( messages[i], messageFilters ) )
            {
                messageList.add( messages[i] );
            }
        }

        if ( messageList.size() == 0 )
            throw new ScriptException( "Failed to find any email messages that met the criteria" );
            
        Collections.sort( messageList, new DateComparator() );

        String messageContent = null;
        String contentType = messageList.get( 0 ).getContentType();

        if ( contentType.startsWith( "text/" ) )
            messageContent = messageList.get( 0 ).getContent().toString();
        else if ( messageList.get( 0 ).isMimeType( "multipart/*" ) )
            messageContent = getTextFromMimeMultipart( (MimeMultipart) messageList.get( 0 ).getContent() );
        else
            messageContent = messageList.get( 0 ).getContent().getClass().getName();

        messageWrapper = new MessageWrapper( messageList.size(), messageList.get( 0 ).getFrom()[0].toString(), messageList.get( 0 ).getSubject(), messageContent, contentType );

        emailFolder.close( false );
        store.close();
    }
    catch ( Exception e )
    {
        e.printStackTrace();
        throw new ScriptException( "Failed to find email" );
    }

    return messageWrapper;
}
 
Example 13
Source File: cfMailFolderMessagesData.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
public cfQueryResultData listFolderMessages( cfImapConnection imapConnection, String rootFolder, int startRow, int totalMessages, boolean reverseOrder ) {
	cfQueryResultData query = new cfQueryResultData( new String[]{"subject","id","rxddate","sentdate","from","to","cc","bcc","size","lines","answered","deleted","draft","flagged","recent","seen"}, "CFIMAP" );

	try{
		Folder	folderToList;
		if ( rootFolder == null || rootFolder.length() == 0 )
			folderToList = imapConnection.mailStore.getDefaultFolder();
		else
			folderToList = imapConnection.mailStore.getFolder(rootFolder);
		
		if ( (folderToList.getType() & Folder.HOLDS_MESSAGES) != 0){
		
			if ( !folderToList.isOpen() )
				folderToList.open( Folder.READ_ONLY );
			
			Message[] messageArray;
			if ( startRow != -1 ){
				
				int folderCount = folderToList.getMessageCount();
				int start, end;
				if ( !reverseOrder ){
					start = startRow;
					if ( folderCount < (startRow+totalMessages-1) ){
						start = startRow;
						end = folderCount; 
					}else{
						end = startRow + totalMessages - 1;
					}
				}else{
					end = folderCount - startRow + 1;
					if ( folderCount < (startRow+totalMessages-1) ){ 
						start = 1;
					}else{
						start = folderCount - startRow - totalMessages + 2;
					}
					
				}
				
				messageArray = folderToList.getMessages( start, end );
				imapConnection.setTotalMessages( folderCount );
				
				
			}else{
				messageArray = folderToList.getMessages();
				imapConnection.setTotalMessages( messageArray.length );
			}

			// To improve performance, pre-fetch all of the message items
			// used by the CFIMAP list action. This will retrieve all of the
			// items for all of the messages with one single FETCH command.
			FetchProfile fp = new FetchProfile();
			fp.add(FetchProfile.Item.ENVELOPE);
			fp.add(FetchProfile.Item.FLAGS);
			fp.add(FetchProfile.Item.CONTENT_INFO);
			folderToList.fetch(messageArray, fp);
			List<Map<String, cfData>>	vectorMessages = new ArrayList<Map<String, cfData>>(messageArray.length);
			
			if ( reverseOrder ){
				int msgIndex = messageArray.length-1;
				for (int i = 0; i < messageArray.length; i++)
					vectorMessages.add( extractMessage( messageArray[msgIndex--] ) );
				
			}else{
				for (int i = 0; i < messageArray.length; i++)
					vectorMessages.add( extractMessage( messageArray[i] ) );
			}
			
			folderToList.close(false);
			query.populateQuery( vectorMessages );
		}

	}catch(Exception E){
		cfEngine.log( E.getMessage() );
		imapConnection.setStatus( false, E.getMessage() );
	}
	
	return query;
}
 
Example 14
Source File: cfPOP3.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
private void readMessages( cfSession _Session, Folder popFolder, cfQueryResultData popData, int _start, int _max, boolean GetAll, File attachmentDir )  throws cfmRunTimeException	{
  try{
  	int maxRows = _max;
  	int startRow = _start;
  	String messageNumber = getDynamic(_Session,"MESSAGENUMBER").getString();
  	boolean containsUID = containsAttribute( "UID" );
  	boolean usingMessageNumber = messageNumber.length() > 0;
  	int msgCount = popFolder.getMessageCount();
  	
  	// if MAXROWS is not specified, or UID or MESSAGENUMBER is, then we want to get all the messages
  	if ( _max == -1 || containsUID || usingMessageNumber ){
  		maxRows = msgCount;
  	}
  	if ( containsUID || usingMessageNumber ){
  		startRow = 1;
  	}
  	
  	if ( msgCount != 0 && startRow > msgCount ){
  		throw newRunTimeException( "The value of STARTROW must not be greater than the total number of messages in the folder, " + popFolder.getMessageCount() + "." );
  	}
  	
  	Message[] listOfMessages;
  	if ( !usingMessageNumber ){
  		listOfMessages = popFolder.getMessages();
  	}else{
  		listOfMessages = popFolder.getMessages( getMessageList( messageNumber ) );
  	}
  	
    FetchProfile fProfile = new FetchProfile();
    fProfile.add( FetchProfile.Item.ENVELOPE );
    fProfile.add(UIDFolder.FetchProfileItem.UID);
    popFolder.fetch( listOfMessages, fProfile );
    
    if ( containsUID ){
      String[] messageUIDList = getMessageUIDList( getDynamic(_Session,"UID").getString() );
    
      for ( int x=0; x < listOfMessages.length; x++ ){
        if ( messageUIDList.length == 0 || messageUIDValid( messageUIDList, getMessageUID( popFolder, listOfMessages[x] ) ) ){
          populateMessage( _Session, listOfMessages[x], popData, GetAll, attachmentDir, popFolder );
        }
      }
    }else{
			popFolder.fetch( listOfMessages, fProfile );
			int end = startRow -1 + maxRows;
			if ( end > listOfMessages.length ){
				end = listOfMessages.length;
			}
			for ( int x=startRow-1; x < end; x++ ){
				populateMessage( _Session, listOfMessages[x], popData, GetAll, attachmentDir, popFolder );
			}
    }
  }catch(Exception E){
    if ( E.getMessage() != null )
        throw newRunTimeException( E.getMessage() );
    else
  	  throw newRunTimeException( E.toString() );
  }

}