Java Code Examples for javax.mail.Folder#HOLDS_MESSAGES

The following examples show how to use javax.mail.Folder#HOLDS_MESSAGES . 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: 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 2
Source File: JavamailService.java    From lemon with Apache License 2.0 6 votes vote down vote up
public void receiveByFolder(Folder folder, JavamailConfig javamailConfig)
        throws MessagingException, IOException {
    logger.info("receive : {}", folder);

    if ((Folder.HOLDS_MESSAGES & folder.getType()) != 0) {
        this.receiveMessageByFolder(folder, javamailConfig);
    }

    if ((Folder.HOLDS_FOLDERS & folder.getType()) != 0) {
        for (Folder childFolder : folder.list()) {
            this.receiveByFolder(childFolder, javamailConfig);
        }
    }

    if (folder.isOpen()) {
        // 关闭资源
        folder.close(false);
    }
}
 
Example 3
Source File: StoreCopier.java    From mnIMAPSync with Apache License 2.0 6 votes vote down vote up
/**
 * Once the folder structure has been created it copies messages recursively from the root
 * folder.
 */
private void copySourceMessages(IMAPFolder sourceFolder) throws MessagingException {
    if (sourceFolder != null) {
        final String sourceFolderName = sourceFolder.getFullName();
        final String targetFolderName = sourceFolderNameToTarget(sourceFolderName, sourceIndex,
            targetIndex);
        if ((sourceFolder.getType() & Folder.HOLDS_MESSAGES) == Folder.HOLDS_MESSAGES) {
            //Manage Servers with public/read only folders.
            try {
                sourceFolder.open(Folder.READ_WRITE);
            } catch (ReadOnlyFolderException ex) {
                sourceFolder.open(Folder.READ_ONLY);
            }
            if (sourceFolder.getMode() != Folder.READ_ONLY) {
                sourceFolder.expunge();
            }
            ///////////////////////
            final int messageCount = sourceFolder.getMessageCount();
            sourceFolder.close(false);
            int pos = 1;
            while (pos + MNIMAPSync.BATCH_SIZE <= messageCount) {
                //Copy messages
                service.execute(new MessageCopier(this, sourceFolderName, targetFolderName, pos,
                        pos + MNIMAPSync.BATCH_SIZE, targetIndex.getFolderMessages(
                                targetFolderName)));
                pos = pos + MNIMAPSync.BATCH_SIZE;
            }
            service.execute(new MessageCopier(this, sourceFolderName, targetFolderName, pos,
                    messageCount,
                    targetIndex.getFolderMessages(targetFolderName)));
        }
        //Folder recursion. Get all children
        if ((sourceFolder.getType() & Folder.HOLDS_FOLDERS) == Folder.HOLDS_FOLDERS) {
            for (Folder child : sourceFolder.list()) {
                copySourceMessages((IMAPFolder) child);
            }
        }
    }
}
 
Example 4
Source File: JavaxMailStorage.java    From mail-importer with Apache License 2.0 5 votes vote down vote up
public FolderIterator(JavaxMailFolder folder) {
  this.folder = folder;
  logger.fine(() -> "Opening folder:" + folder.getName());
  if (!folder.isOpen()) {
    folder.open(Folder.READ_ONLY);
  }
  this.messageIterator = (folder.getType() & Folder.HOLDS_MESSAGES) > 0
      ? new MessageIterator()
      : Collections.emptyIterator();
  this.subfolderIterator = (folder.getType() & Folder.HOLDS_FOLDERS) > 0
      ? new SubfolderIterator()
      : Collections.emptyIterator();
}
 
Example 5
Source File: cfMailMessageData.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public void getMessage( cfImapConnection imapConnection, String rootFolder, long messageID, String _attachURI, String _attachDIR ) throws cfmRunTimeException {
	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 );

			boolean bResult = false;
			if ( folderToList instanceof UIDFolder )	
				bResult = extractMessage( ((UIDFolder)folderToList).getMessageByUID( messageID ), messageID, _attachURI, _attachDIR );
			else
				bResult = extractMessage( folderToList.getMessage( (int)messageID ), messageID, _attachURI, _attachDIR );
			
			if ( !bResult )	imapConnection.setStatus( false, "Message does not exist" );
			else imapConnection.setStatus( true, "" );
			
			folderToList.close(false);
		}

	}catch(Exception E){
		imapConnection.setStatus( false, E.getMessage() );
	}
}
 
Example 6
Source File: ParallelPollingIMAPMailSource.java    From elasticsearch-imap with Apache License 2.0 5 votes vote down vote up
protected void recurseFolders(final Folder folder, final Pattern pattern) throws MessagingException, IOException {

        if (folder != null) {

            if (es == null || es.isShutdown() || es.isTerminated() || Thread.currentThread().isInterrupted()) {

                logger.warn("Stop processing of mails due to mail source is closed");
                return;

            }

            if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {

                if (pattern != null && !pattern.matcher(folder.getFullName()).matches()) {
                    logger.debug("Pattern {} does not match {}", pattern.pattern(), folder.getFullName());
                    return;
                }
                IMAPUtils.open(folder);

                try {
                    fetch(folder);
                } finally {
                    IMAPUtils.close(folder);
                    logger.debug("fetch {} done", folder.getFullName());
                }
            }

            if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
                for (final Folder subfolder : folder.list()) {

                    recurseFolders(subfolder, pattern);

                }
            }

        }

    }
 
Example 7
Source File: ParallelPollingPOPMailSource.java    From elasticsearch-imap with Apache License 2.0 5 votes vote down vote up
protected void recurseFolders(final Folder folder, final Pattern pattern) throws MessagingException, IOException {

        if (folder != null) {

            if (es == null || es.isShutdown() || es.isTerminated() || Thread.currentThread().isInterrupted()) {

                logger.warn("Stop processing of mails due to mail source is closed");
                return;

            }

            if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {

                if (pattern != null && !pattern.matcher(folder.getFullName()).matches()) {
                    logger.debug("Pattern {} does not match {}", pattern.pattern(), folder.getFullName());
                    return;
                }
                IMAPUtils.open(folder);
                try {
                    fetch(folder);
                } finally {
                    IMAPUtils.close(folder);
                }
            }

            if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
                for (final Folder subfolder : folder.list()) {

                    recurseFolders(subfolder, pattern);

                }
            }

        }

    }
 
Example 8
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 9
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 10
Source File: MailConnection.java    From hop with Apache License 2.0 4 votes vote down vote up
/**
 * Open the folder.
 *
 * @param foldername    the name of the folder to open
 * @param defaultFolder true to open the default folder (INBOX)
 * @param write         open the folder in write mode
 * @throws HopException if something went wrong.
 */
public void openFolder( String foldername, boolean defaultFolder, boolean write ) throws HopException {
  this.write = write;
  try {
    if ( getFolder() != null ) {
      // A folder is already opened
      // before make sure to close it
      closeFolder( true );
    }

    if ( defaultFolder ) {
      if ( protocol == MailConnectionMeta.PROTOCOL_MBOX ) {
        this.folder = this.store.getDefaultFolder();
      } else {
        // get the default folder
        this.folder = getRecursiveFolder( MailConnectionMeta.INBOX_FOLDER );
      }

      if ( this.folder == null ) {
        throw new HopException( BaseMessages.getString( PKG, "JobGetMailsFromPOP.InvalidDefaultFolder.Label" ) );
      }

      if ( ( folder.getType() & Folder.HOLDS_MESSAGES ) == 0 ) {
        throw new HopException( BaseMessages.getString( PKG, "MailConnection.DefaultFolderCanNotHoldMessage" ) );
      }
    } else {
      // Open specified Folder (for IMAP/MBOX)
      if ( this.protocol == MailConnectionMeta.PROTOCOL_IMAP
        || this.protocol == MailConnectionMeta.PROTOCOL_MBOX ) {
        this.folder = getRecursiveFolder( foldername );
      }
      if ( this.folder == null || !this.folder.exists() ) {
        throw new HopException( BaseMessages.getString( PKG, "JobGetMailsFromPOP.InvalidFolder.Label" ) );
      }
    }
    if ( this.write ) {
      if ( log.isDebug() ) {
        log.logDebug( BaseMessages.getString(
          PKG, "MailConnection.OpeningFolderInWriteMode.Label", getFolderName() ) );
      }
      this.folder.open( Folder.READ_WRITE );
    } else {
      if ( log.isDebug() ) {
        log.logDebug( BaseMessages.getString(
          PKG, "MailConnection.OpeningFolderInReadMode.Label", getFolderName() ) );
      }
      this.folder.open( Folder.READ_ONLY );
    }

    if ( log.isDetailed() ) {
      log.logDetailed( BaseMessages.getString( PKG, "JobGetMailsFromPOP.FolderOpened.Label", getFolderName() ) );
    }
    if ( log.isDebug() ) {
      // display some infos on folder
      //CHECKSTYLE:LineLength:OFF
      log.logDebug( BaseMessages.getString( PKG, "JobGetMailsFromPOP.FolderOpened.Name", getFolderName() ) );
      log.logDebug( BaseMessages.getString( PKG, "JobGetMailsFromPOP.FolderOpened.FullName", this.folder.getFullName() ) );
      log.logDebug( BaseMessages.getString( PKG, "JobGetMailsFromPOP.FolderOpened.Url", this.folder.getURLName().toString() ) );
      log.logDebug( BaseMessages.getString( PKG, "JobGetMailsFromPOP.FolderOpened.Subscribed", "" + this.folder.isSubscribed() ) );
    }

  } catch ( Exception e ) {
    throw new HopException( defaultFolder
      ? BaseMessages.getString( PKG, "JobGetMailsFromPOP.Error.OpeningDefaultFolder" )
      : BaseMessages.getString( PKG, "JobGetMailsFromPOP.Error.OpeningFolder", foldername ), e );
  }
}
 
Example 11
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 12
Source File: MailConnection.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
/**
 * Open the folder.
 *
 * @param foldername
 *          the name of the folder to open
 * @param defaultFolder
 *          true to open the default folder (INBOX)
 * @param write
 *          open the folder in write mode
 * @throws KettleException
 *           if something went wrong.
 */
public void openFolder( String foldername, boolean defaultFolder, boolean write ) throws KettleException {
  this.write = write;
  try {
    if ( getFolder() != null ) {
      // A folder is already opened
      // before make sure to close it
      closeFolder( true );
    }

    if ( defaultFolder ) {
      if ( protocol == MailConnectionMeta.PROTOCOL_MBOX ) {
        this.folder = this.store.getDefaultFolder();
      } else {
        // get the default folder
        this.folder = getRecursiveFolder( MailConnectionMeta.INBOX_FOLDER );
      }

      if ( this.folder == null ) {
        throw new KettleException( BaseMessages.getString( PKG, "JobGetMailsFromPOP.InvalidDefaultFolder.Label" ) );
      }

      if ( ( folder.getType() & Folder.HOLDS_MESSAGES ) == 0 ) {
        throw new KettleException( BaseMessages.getString( PKG, "MailConnection.DefaultFolderCanNotHoldMessage" ) );
      }
    } else {
      // Open specified Folder (for IMAP/MBOX)
      if ( this.protocol == MailConnectionMeta.PROTOCOL_IMAP
        || this.protocol == MailConnectionMeta.PROTOCOL_MBOX ) {
        this.folder = getRecursiveFolder( foldername );
      }
      if ( this.folder == null || !this.folder.exists() ) {
        throw new KettleException( BaseMessages.getString( PKG, "JobGetMailsFromPOP.InvalidFolder.Label" ) );
      }
    }
    if ( this.write ) {
      if ( log.isDebug() ) {
        log.logDebug( BaseMessages.getString(
          PKG, "MailConnection.OpeningFolderInWriteMode.Label", getFolderName() ) );
      }
      this.folder.open( Folder.READ_WRITE );
    } else {
      if ( log.isDebug() ) {
        log.logDebug( BaseMessages.getString(
          PKG, "MailConnection.OpeningFolderInReadMode.Label", getFolderName() ) );
      }
      this.folder.open( Folder.READ_ONLY );
    }

    if ( log.isDetailed() ) {
      log.logDetailed( BaseMessages.getString( PKG, "JobGetMailsFromPOP.FolderOpened.Label", getFolderName() ) );
    }
    if ( log.isDebug() ) {
      // display some infos on folder
      //CHECKSTYLE:LineLength:OFF
      log.logDebug( BaseMessages.getString( PKG, "JobGetMailsFromPOP.FolderOpened.Name", getFolderName() ) );
      log.logDebug( BaseMessages.getString( PKG, "JobGetMailsFromPOP.FolderOpened.FullName", this.folder.getFullName() ) );
      log.logDebug( BaseMessages.getString( PKG, "JobGetMailsFromPOP.FolderOpened.Url", this.folder.getURLName().toString() ) );
      log.logDebug( BaseMessages.getString( PKG, "JobGetMailsFromPOP.FolderOpened.Subscribed", "" + this.folder.isSubscribed() ) );
    }

  } catch ( Exception e ) {
    throw new KettleException( defaultFolder
      ? BaseMessages.getString( PKG, "JobGetMailsFromPOP.Error.OpeningDefaultFolder" )
      : BaseMessages.getString( PKG, "JobGetMailsFromPOP.Error.OpeningFolder", foldername ), e );
  }
}
 
Example 13
Source File: IMAPUtils.java    From elasticsearch-imap with Apache License 2.0 3 votes vote down vote up
public static void open(final Folder folder) throws MessagingException {

        if (folder != null && folder.exists() && !folder.isOpen() && (folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
            folder.open(Folder.READ_ONLY);
        }

    }