Java Code Examples for javax.mail.FetchProfile

The following examples show how to use javax.mail.FetchProfile. These examples are extracted from open source projects. 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 Project: development   Source File: MailReader.java    License: 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 Project: mnIMAPSync   Source File: MessageId.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * Adds required headers to fetch profile
     */
    public static FetchProfile addHeaders(FetchProfile fetchProfile) {
        fetchProfile.add(FetchProfile.Item.ENVELOPE);
        //Some servers respond to get a header request with a partial response of the header
        //when hMailServer is fetched for To or From, it returns only the first entry,
        //so when compared with other server versions, e-mails appear to be different.
        fetchProfile.add(IMAPFolder.FetchProfileItem.HEADERS);
        //If using the header consructor add this for performance.
//        for (String header : new String[]{
//            MessageId.HEADER_MESSAGE_ID,
//            MessageId.HEADER_SUBJECT,
//            MessageId.HEADER_FROM,
//            MessageId.HEADER_TO}) {
//            fetchProfile.add(header.toUpperCase());
//        }
        return fetchProfile;
    }
 
Example 3
Source Project: mail-importer   Source File: JavaxMailFolder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void fetch(Message[] msgs, FetchProfile fp)
    throws RuntimeMessagingException {
  try {
    delegate.fetch(msgs, fp);
  } catch (MessagingException e) {
    throw new RuntimeMessagingException(e);
  }
}
 
Example 4
Source Project: mnIMAPSync   Source File: FolderCrawler.java    License: 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 5
Source Project: mnIMAPSync   Source File: MessageDeleter.java    License: 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 6
Source Project: FairEmail   Source File: FetchItem.java    License: GNU General Public License v3.0 4 votes vote down vote up
public FetchItem(String name, FetchProfile.Item fetchProfileItem) {
this.name = name;
this.fetchProfileItem = fetchProfileItem;
   }
 
Example 7
Source Project: FairEmail   Source File: FetchItem.java    License: GNU General Public License v3.0 4 votes vote down vote up
public FetchProfile.Item getFetchProfileItem() {
return fetchProfileItem;
   }
 
Example 8
Source Project: scipio-erp   Source File: JavaMailContainer.java    License: 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 9
Source Project: development   Source File: MailReader.java    License: 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 10
Source Project: development   Source File: MailReader.java    License: 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 11
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 Project: openbd-core   Source File: cfPOP3.java    License: 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 13
Source Project: openbd-core   Source File: cfPOP3.java    License: 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 14
@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 15
Source Project: javamail-mock2   Source File: POP3MockFolder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void fetch(final Message[] msgs, final FetchProfile fp) throws MessagingException {
    // just do nothing
}
 
Example 16
Source Project: javamail-mock2   Source File: IMAPMockFolder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void fetch(final Message[] msgs, final FetchProfile fp) throws MessagingException {
    abortIdle();
    // do nothing more
}