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

The following examples show how to use javax.mail.Folder#fetch() . 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: MailReader.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to the mail server and delete all mails.
 */
public void deleteMails() throws MessagingException {
    Folder folder = getStore().getFolder(MAIL_INBOX);
    folder.open(Folder.READ_WRITE);

    // Get folder's list of messages.
    Message[] messages = folder.getMessages();

    // Retrieve message headers for each message in folder.
    FetchProfile profile = new FetchProfile();
    profile.add(FetchProfile.Item.ENVELOPE);
    folder.fetch(messages, profile);

    for (Message message : messages) {
        message.setFlag(Flags.Flag.DELETED, true);
    }
    folder.close(true);

}
 
Example 2
Source File: FolderCrawler.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
public void run() {
    long indexedMessages = 0L;
    long skippedMessages = 0L;
    try {
        final Folder folder = store.getFolder(folderName);
        folder.open(Folder.READ_ONLY);
        final Message[] messages = folder.getMessages(start, end);
        folder.fetch(messages, MessageId.addHeaders(new FetchProfile()));
        for (Message message : messages) {
            //Don't bother crawling if index has exceptions. Process won't continue
            if (index.hasCrawlException()) {
                return;
            }
            try {
                final MessageId messageId = new MessageId(message);
                if (index.getFolderMessages(folderName).add(messageId)) {
                    indexedMessages++;
                } else {
                    skippedMessages++;
                }
            } catch (MessageId.MessageIdException ex) {
                if (ex.getCause() != null) {
                    throw new MessagingException();
                }
                skippedMessages++;
            }
        }
        folder.close(false);
    } catch (MessagingException messagingException) {
        index.addCrawlException(messagingException);
    }
    index.updatedIndexedMessageCount(indexedMessages);
    index.updatedSkippedMessageCount(skippedMessages);
}
 
Example 3
Source File: MessageDeleter.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
public void run() {
    long deleted = 0L;
    long skipped = 0L;
    try {
        final Folder targetFolder = storeDeleter.getTargetStore().getFolder(targetFolderName);
        //Opens a new connection per Thread
        targetFolder.open(Folder.READ_WRITE);
        final Message[] targetMessages = targetFolder.getMessages(start, end);
        targetFolder.fetch(targetMessages, MessageId.addHeaders(new FetchProfile()));
        for (Message message : targetMessages) {
            try {
                final MessageId id = new MessageId(message);
                if (!sourceFolderMessages.contains(id)) {
                    message.setFlag(Flags.Flag.DELETED, true);
                    deleted++;
                } else {
                    skipped++;
                }
            } catch (MessageId.MessageIdException ex) {
                //Usually messages that ran into this exception are spammy, so we skip them.
                skipped++;
            }
        }
        //Close folder and expunge flagged messages
        //Expunge only if folder is read write
        if (targetFolder.getMode() == Folder.READ_ONLY) {
            targetFolder.close(false);
        } else {
            targetFolder.close(expunge);
        }
    } catch (MessagingException messagingException) {
        Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, messagingException);
    }
    storeDeleter.updatedMessagesDeletedCount(deleted);
    storeDeleter.updateMessagesSkippedCount(skipped);
}
 
Example 4
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 5
Source File: MailReader.java    From development with Apache License 2.0 4 votes vote down vote up
/**
 * Get the content of the last message with the given subject.
 *
 * @param subject
 *            the subject
 * @return the content of the last message with the given subject
 */
public String getLastMailContentWithSubject(String subject)
        throws MessagingException {
    // Download message headers from server.
    int retries = 0;
    String content = null;
    while (retries < 40) {

        // Open main "INBOX" folder.
        Folder folder = getStore().getFolder(MAIL_INBOX);
        folder.open(Folder.READ_WRITE);

        // Get folder's list of messages.
        Message[] messages = folder.getMessages();

        // Retrieve message headers for each message in folder.
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.ENVELOPE);
        folder.fetch(messages, profile);

        for (Message message : messages) {
            if (message.getSubject().equals(subject)) {
                content = getMessageContent(message);
            }
        }
        folder.close(true);

        if (content != null) {
            return content;
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // ignored
        }
        retries++;
    }

    return "";
}
 
Example 6
Source File: MailReader.java    From development with Apache License 2.0 4 votes vote down vote up
public String[] readPassAndKeyFromEmail(boolean delete, String userName)
        throws MessagingException {
    // Download message headers from server.
    int retries = 0;
    String userPass = null;
    String userKey = null;
    while (retries < 40 && userPass == null) {

        // Open main "INBOX" folder.
        Folder folder = getStore().getFolder(MAIL_INBOX);
        folder.open(Folder.READ_WRITE);

        // Get folder's list of messages.
        Message[] messages = folder.getMessages();

        // Retrieve message headers for each message in folder.
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.ENVELOPE);
        folder.fetch(messages, profile);

        for (Message message : messages) {
            if (message.getSubject().equals(MAIL_SUBJECT_USER_ACCOUNT_CREATED_EN)) {
                String content = getMessageContent(message);
                String userNameFromEmail = readInformationFromGivenMail(MAIL_BODY_USERNAME_PATTERN_EN, content);
                if (userName.equals(userNameFromEmail)) {
                    userKey = readInformationFromGivenMail(MAIL_BODY_USERKEY_PATTERN_EN, content);
                    userPass = readInformationFromGivenMail(MAIL_BODY_PASSWORD_PATTERN_EN, content);
                    if (delete) {
                        message.setFlag(Flag.DELETED, true);
                    }
                    break;
                }
            }
        }
        folder.close(true);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // ignored
        }
        retries++;
    }

    return new String[] {userKey, userPass};
}
 
Example 7
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 8
Source File: cfPOP3.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
private void deleteMessagesFromServer( cfSession _Session ) throws cfmRunTimeException {

		//--[ Get Message Store
		Store popStore			= openConnection( _Session );

		//--[ Open up the Folder:INBOX and retrieve the headers
		Folder popFolder 	= openFolder( _Session, popStore );

    try{
      Message[] listOfMessages  = popFolder.getMessages();
      FetchProfile fProfile = new FetchProfile();
      fProfile.add( FetchProfile.Item.ENVELOPE );
      
      if ( containsAttribute( "UID" ) ){
        String[] messageUIDList = getMessageUIDList( getDynamic(_Session,"UID").getString() );
        fProfile.add(UIDFolder.FetchProfileItem.UID);
        popFolder.fetch( listOfMessages, fProfile );
  
        for ( int x=0; x < listOfMessages.length; x++ ){
          if ( messageUIDValid( messageUIDList, getMessageUID( popFolder, listOfMessages[x] ) ) ){
            listOfMessages[x].setFlag( Flags.Flag.DELETED, true );
          }
        }
        
      }else if ( containsAttribute( "MESSAGENUMBER" ) ){
    		int[] messageList	= getMessageList( getDynamic(_Session,"MESSAGENUMBER").getString() );
  			popFolder.fetch( listOfMessages, fProfile );
    
   			for ( int x=0; x < listOfMessages.length; x++ ){
   				if ( messageIDValid(messageList, listOfMessages[x].getMessageNumber() ) ){
   					listOfMessages[x].setFlag( Flags.Flag.DELETED, true );
   				}
   			}
   			
      }else{
  	    throw newRunTimeException( "Either MESSAGENUMBER or UID attribute must be specified when ACTION=DELETE" );
      }
    }catch(Exception ignore){}

    //--[ Close off the folder		
		closeFolder( popFolder );
		closeConnection( popStore );
	}
 
Example 9
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() );
  }

}
 
Example 10
Source File: MailAccountServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public int fetchEmails(EmailAccount mailAccount, boolean unseenOnly)
    throws MessagingException, IOException {

  if (mailAccount == null) {
    return 0;
  }

  log.debug(
      "Fetching emails from host: {}, port: {}, login: {} ",
      mailAccount.getHost(),
      mailAccount.getPort(),
      mailAccount.getLogin());

  com.axelor.mail.MailAccount account = null;
  if (mailAccount.getServerTypeSelect().equals(EmailAccountRepository.SERVER_TYPE_IMAP)) {
    account =
        new ImapAccount(
            mailAccount.getHost(),
            mailAccount.getPort().toString(),
            mailAccount.getLogin(),
            mailAccount.getPassword(),
            getSecurity(mailAccount));
  } else {
    account =
        new Pop3Account(
            mailAccount.getHost(),
            mailAccount.getPort().toString(),
            mailAccount.getLogin(),
            mailAccount.getPassword(),
            getSecurity(mailAccount));
  }

  MailReader reader = new MailReader(account);
  final Store store = reader.getStore();
  final Folder inbox = store.getFolder("INBOX");

  // open as READ_WRITE to mark messages as seen
  inbox.open(Folder.READ_WRITE);

  // find all unseen messages
  final FetchProfile profile = new FetchProfile();
  javax.mail.Message[] messages;
  if (unseenOnly) {
    final FlagTerm unseen = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
    messages = inbox.search(unseen);
  } else {
    messages = inbox.getMessages();
  }

  profile.add(FetchProfile.Item.ENVELOPE);

  // actually fetch the messages
  inbox.fetch(messages, profile);
  log.debug("Total emails unseen: {}", messages.length);

  int count = 0;
  for (javax.mail.Message message : messages) {
    if (message instanceof MimeMessage) {
      MailParser parser = new MailParser((MimeMessage) message);
      parser.parse();
      createMessage(mailAccount, parser, message.getSentDate());
      count++;
    }
  }

  log.debug("Total emails fetched: {}", count);

  return count;
}
 
Example 11
Source File: ParallelPollingIMAPMailSource.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 {

        logger.debug("processMessageSlice() started with " + start + "/" + end + "/" + folderName);
        final long startTime = System.currentTimeMillis();
        final Store store = Session.getInstance(props).getStore();
        store.connect(user, password);
        final Folder folder = store.getFolder(folderName);
        final UIDFolder uidfolder = (UIDFolder) folder;

        IMAPUtils.open(folder);

        try {

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

            logger.debug("folder fetch done");

            long highestUid = 0;
            int processedCount = 0;

            for (final Message m : msgs) {
                try {

                    IMAPUtils.open(folder);
                    final long uid = uidfolder.getUID(m);

                    mailDestination.onMessage(m);

                    highestUid = Math.max(highestUid, uid);
                    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;
            final ProcessResult pr = new ProcessResult(highestUid, processedCount, endTime - startTime);
            logger.debug("processMessageSlice() ended with " + pr);
            return pr;

        } finally {

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

    }
 
Example 12
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);
        }

    }