javax.mail.UIDFolder Java Examples

The following examples show how to use javax.mail.UIDFolder. 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: cfImapConnection.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
public void changeStatus( String folderName, long mailIDs[], Flags.Flag newFlag, boolean value ){
  try{
  
    Folder folderToUse = mailStore.getFolder(folderName);
    folderToUse.open( Folder.READ_WRITE );
    
    Flags f = new Flags();
    f.add( newFlag );
	
	Message mlist[];
	if ( folderToUse instanceof UIDFolder )
		mlist = ((UIDFolder)folderToUse).getMessagesByUID( mailIDs );
	else
		mlist = folderToUse.getMessages( returnToInts(mailIDs) );
	
	for ( int x=0; x < mlist.length; x++ )
		mlist[x].setFlags( f, value );
    
    folderToUse.close( true );
	setData( "succeeded", 	cfBooleanData.TRUE );
  
  } catch (Exception E ){
	setData( "errortext", 	new cfStringData( E.getMessage() ) );
	setData( "succeeded", 	cfBooleanData.FALSE );
  }
}
 
Example #2
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 #3
Source File: MailboxFolder.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
public synchronized Message[] getByIds(final long start, final long end/* final Folder folder*/) {
    checkExists();
    final List<MockMessage> sms = new ArrayList<MockMessage>();
    int num = 0;

    MockMessage lastMsg = null;

    for (final MockMessage mockMessage : new TreeSet<MockMessage>(messages.values())) {

        lastMsg = mockMessage;

        if (end == UIDFolder.LASTUID) {
            if (getMessageCount() != 1 && mockMessage.getMockid() < start) { // TODO
                                                                             // check?
                continue;
            }
        } else {
            if (mockMessage.getMockid() < start || mockMessage.getMockid() > end) {
                continue;
            }
        }

        mockMessage.setMessageNumber(++num);
        // mockMessage.setFolder(folder);
        sms.add(mockMessage);
    }

    if (end == UIDFolder.LASTUID && sms.size() == 0) {
        lastMsg.setMessageNumber(++num);
        // lastMsg.setFolder(folder);
        sms.add(lastMsg);
    }

    logger.debug("getByIds(" + start + "," + end + " for " + getFullName() + " returns " + sms.size());
    return sms.toArray(new Message[sms.size()]);
}
 
Example #4
Source File: IMAPTestCase.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_WRITE);
    Assert.assertEquals(3, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));

    inbox.close(true);

    Assert.assertEquals(3, inbox.getMessageCount());

    inbox.open(Folder.READ_WRITE);
    inbox.getMessage(1).setFlag(Flag.DELETED, true);

    inbox.close(true);

    Assert.assertEquals(2, inbox.getMessageCount());
    Assert.assertTrue(inbox instanceof UIDFolder);
    inbox.open(Folder.READ_WRITE);
    Assert.assertEquals(12L, ((UIDFolder) inbox).getUID(inbox.getMessage(1)));
    inbox.close(true);
}
 
Example #5
Source File: cfMailFolderMessagesData.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
private Map<String, cfData> extractMessage( Message Mess ){
 	Map<String, cfData> HT	= new FastMap<String, cfData>();
	
try{
	HT.put( "subject", 	new cfStringData( Mess.getSubject() ) );
	
	Folder parentFolder	= Mess.getFolder();
	if ( parentFolder instanceof UIDFolder )
		HT.put( "id",	new cfNumberData( ((UIDFolder)parentFolder).getUID( Mess) ) );
	else
		HT.put( "id",	new cfNumberData( Mess.getMessageNumber() ) );
	
	//--[ Get the FROM field
	Address[] from	= Mess.getFrom();
	if ( from != null && from.length > 0 ){
		cfStructData sdFrom	= new cfStructData();
		
		String name = ((InternetAddress)from[0]).getPersonal();
		if ( name != null )
				sdFrom.setData( "name", new cfStringData( name ) );
		
		sdFrom.setData( "email", new cfStringData( ((InternetAddress)from[0]).getAddress() ) );
		HT.put( "from", sdFrom );
	}
	
	//--[ Get the TO/CC/BCC field
	cfArrayData	AD	= extractAddresses( Mess.getRecipients(Message.RecipientType.TO) );
	if ( AD != null )
		HT.put( "to", AD );
    else
      HT.put( "to", cfNullData.NULL );
      

	AD	= extractAddresses( Mess.getRecipients(Message.RecipientType.CC) );
	if ( AD != null )
		HT.put( "cc", AD );		
    else
      HT.put( "cc", cfNullData.NULL );

	AD	= extractAddresses( Mess.getRecipients(Message.RecipientType.BCC) );
	if ( AD != null )
		HT.put( "bcc", AD );
    else
      HT.put( "bcc", cfNullData.NULL );

	//--[ Set the flags
	HT.put( "answered",	cfBooleanData.getcfBooleanData( Mess.isSet( Flags.Flag.ANSWERED ) ) );
	HT.put( "deleted",	cfBooleanData.getcfBooleanData( Mess.isSet( Flags.Flag.DELETED ) ) );
	HT.put( "draft",		cfBooleanData.getcfBooleanData( Mess.isSet( Flags.Flag.DRAFT ) ) );
	HT.put( "flagged",	cfBooleanData.getcfBooleanData( Mess.isSet( Flags.Flag.FLAGGED ) ) );
	HT.put( "recent",		cfBooleanData.getcfBooleanData( Mess.isSet( Flags.Flag.RECENT ) ) );
	HT.put( "seen",			cfBooleanData.getcfBooleanData( Mess.isSet( Flags.Flag.SEEN ) ) );

	HT.put( "size",			new cfNumberData( Mess.getSize() ) );
	HT.put( "lines",		new cfNumberData( Mess.getLineCount() ) );

    Date DD = Mess.getReceivedDate();
    if ( DD == null )
			HT.put( "rxddate", 	new cfDateData( System.currentTimeMillis() ) );
	  else
			HT.put( "rxddate", 	new cfDateData( DD.getTime() ) );


    DD = Mess.getSentDate();
    if ( DD == null )
			HT.put( "sentdate", 	new cfDateData( System.currentTimeMillis() ) );
	  else
			HT.put( "sentdate", 	new cfDateData( DD.getTime() ) );

}catch(Exception E){
  com.nary.Debug.printStackTrace( E );
}
	
return HT;  	  
}
 
Example #6
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 #7
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 #8
Source File: IMAPTestCase.java    From javamail-mock2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testDefaultFolder() 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("mock_imaps");
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();
    final Folder inbox = defaultFolder.getFolder("INBOX");

    inbox.open(Folder.READ_WRITE);

    Assert.assertEquals("[INBOX, test]", Arrays.toString(defaultFolder.list()));

    Assert.assertEquals(3, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));

    inbox.close(true);

    Assert.assertEquals(3, inbox.getMessageCount());

    inbox.open(Folder.READ_WRITE);
    inbox.getMessage(1).setFlag(Flag.DELETED, true);

    inbox.close(true);
    inbox.open(Folder.READ_WRITE);
    Assert.assertEquals(2, inbox.getMessageCount());
    Assert.assertTrue(inbox instanceof UIDFolder);
    Assert.assertEquals(12L, ((UIDFolder) inbox).getUID(inbox.getMessage(1)));
    inbox.close(true);
}
 
Example #9
Source File: ImapSessionFolder.java    From greenmail with Apache License 2.0 4 votes vote down vote up
private UIDFolder unwrapUIDFolder() {
    if (folder instanceof UIDFolder) {
        return (UIDFolder) folder;
    }
    throw new IllegalStateException("No UIDFolder supported by "+ folder.getClass());
}
 
Example #10
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);
        }

    }