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

The following examples show how to use javax.mail.Folder#exists() . 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: MailConnection.java    From hop with Apache License 2.0 6 votes vote down vote up
/**
 * Set destination folder
 *
 * @param foldername   destination foldername
 * @param createFolder flag create folder if needed
 * @throws HopException
 */
public void setDestinationFolder( String foldername, boolean createFolder ) throws HopException {
  try {
    String[] folderparts = foldername.split( "/" );
    Folder f = this.getStore().getDefaultFolder();
    // Open destination folder
    for ( int i = 0; i < folderparts.length; i++ ) {
      f = f.getFolder( folderparts[ i ] );
      if ( !f.exists() ) {
        if ( createFolder ) {
          // Create folder
          f.create( Folder.HOLDS_MESSAGES );
        } else {
          throw new HopException( BaseMessages.getString( PKG, "MailConnection.Error.FolderNotFound", foldername ) );
        }
      }
    }
    this.destinationIMAPFolder = f;
  } catch ( Exception e ) {
    throw new HopException( e );
  }
}
 
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: EMailTestServer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public List<EMailMessageModel> getEmailsInFolder(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);
    List<EMailMessageModel> models = new ArrayList<>();
    for (Message msg : newFolder.getMessages()) {
        models.add(createMessageModel(msg));
    }

    return models;
}
 
Example 4
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 5
Source File: cfImapConnection.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
public void createFolder( String newFolder ){
	if ( newFolder.length() == 0 )
		return;
	
   try{
   
     Folder folderToUse = mailStore.getFolder( newFolder );
		
		if ( !folderToUse.exists() ){
			folderToUse.create( Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES );
		}
		
     setData( "succeeded", 	cfBooleanData.TRUE );
   
   } catch (Exception E ){
     setData( "errortext", 	new cfStringData( E.getMessage() ) );
     setData( "succeeded", 	cfBooleanData.FALSE );
   }
	
	setTotalMessages( 0 );
}
 
Example 6
Source File: cfImapConnection.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
public void deleteFolder( String folderToDelete ){
	if ( folderToDelete.length() == 0 )
		return;

   try{
   
     Folder folderToUse = mailStore.getFolder( folderToDelete );
		
		if ( folderToUse.exists() ){
			folderToUse.delete( true );
		}
		
     setData( "succeeded", 	cfBooleanData.TRUE );
     
   } catch (Exception E ){
     setData( "errortext", 	new cfStringData( E.getMessage() ) );
     setData( "succeeded", 	cfBooleanData.FALSE );
   }
	
	setTotalMessages( 0 );
}
 
Example 7
Source File: cfImapConnection.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
public void renameFolder( String oldFolder, String newFolder ){
	
	if ( oldFolder.length() == 0 || newFolder.length() == 0 )
		return;
	
   try{
   
     Folder folderToUse 		= mailStore.getFolder( oldFolder );
		Folder newfolderToUse = mailStore.getFolder( newFolder );
		
		if ( folderToUse.exists() && !newfolderToUse.exists() ){
			folderToUse.renameTo( newfolderToUse );
		}
		
     setData( "succeeded", 	cfBooleanData.TRUE );
   
   } catch (Exception E ){
     setData( "errortext", 	new cfStringData( E.getMessage() ) );
     setData( "succeeded", 	cfBooleanData.FALSE );
   }
	
	setTotalMessages( 0 );
}
 
Example 8
Source File: MailConnection.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Set destination folder
 *
 * @param foldername
 *          destination foldername
 * @param createFolder
 *          flag create folder if needed
 * @throws KettleException
 */
public void setDestinationFolder( String foldername, boolean createFolder ) throws KettleException {
  try {
    String[] folderparts = foldername.split( "/" );
    Folder f = this.getStore().getDefaultFolder();
    // Open destination folder
    for ( int i = 0; i < folderparts.length; i++ ) {
      f = f.getFolder( folderparts[i] );
      if ( !f.exists() ) {
        if ( createFolder ) {
          // Create folder
          f.create( Folder.HOLDS_MESSAGES );
        } else {
          throw new KettleException( BaseMessages.getString( PKG, "MailConnection.Error.FolderNotFound", foldername ) );
        }
      }
    }
    this.destinationIMAPFolder = f;
  } catch ( Exception e ) {
    throw new KettleException( e );
  }
}
 
Example 9
Source File: EMailTestServer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public void generateFolder(String user, String password, String folderName) throws Exception {
    if (server instanceof SmtpServer) {
        throw new Exception("SMTP not applicable for generating folders");
    }

    Store store = server.createStore();
    store.connect(user, password);

    Folder newFolder = store.getFolder(folderName);
    if (! newFolder.exists()) {
        newFolder.create(Folder.HOLDS_MESSAGES);
        assertTrue(newFolder.exists());
    }

    newFolder.open(Folder.READ_WRITE);
    assertTrue(newFolder.isOpen());

    List<MimeMessage> msgs = new ArrayList<>();
    for (int i = 1; i <= 5; ++i) {
        // Use random content to avoid potential residual lingering problems
        String subject = folderName + SPACE + HYPHEN + SPACE + GreenMailUtil.random();
        String body = folderName + NEW_LINE + GreenMailUtil.random();
        GreenMailUser greenUser = greenMail.setUser(user, password);
        msgs.add(createTextMessage(greenUser.getEmail(), "Ben" + i + "@test.com", subject, body)); // Construct message
    }

    newFolder.appendMessages(msgs.toArray(new MimeMessage[0]));
    assertEquals(msgs.size(), newFolder.getMessageCount());
}
 
Example 10
Source File: IMAPMockFolder.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void copyMessages(final Message[] msgs, final Folder folder) throws MessagingException {
    abortIdle();
    checkOpened();
    checkExists();
    if (msgs == null || folder == null || msgs.length == 0) {
        return;
    }

    if (!folder.exists()) {
        throw new FolderNotFoundException(folder.getFullName() + " does not exist", folder);
    }

    folder.appendMessages(msgs);
}
 
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: ParallelPollingPOPMailSource.java    From elasticsearch-imap with Apache License 2.0 4 votes vote down vote up
protected void fetch(final Pattern unusedPattern, final String unusedFolderName) throws MessagingException, IOException {

        logger.debug("fetch() - folderName: {}", "INBOX");

        final Store store = Session.getInstance(props).getStore();
        store.connect(user, password);

        final Folder folder = store.getDefaultFolder();
        try {

            if (!folder.exists()) {
                logger.error("Folder {} does not exist on the server", folder.getFullName());
                return;
            }

            IMAPUtils.open(folder);

            recurseFolders(folder, null);

        } finally {

            IMAPUtils.close(folder);
            IMAPUtils.close(store);
        }
    }
 
Example 13
Source File: AbstractIMAPRiverUnitTest.java    From elasticsearch-imap with Apache License 2.0 4 votes vote down vote up
protected void createInitialIMAPTestdata(final Properties props, final String user, final String password, final int count,
        final boolean deleteall) throws MessagingException {
    final Session session = Session.getInstance(props);
    final Store store = session.getStore();
    store.connect(user, password);
    checkStoreForTestConnection(store);
    final Folder root = store.getDefaultFolder();
    final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS");
    final Folder testrootl2 = testroot.getFolder("Level(2!");

    if (deleteall) {

        deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password);

        if (testroot.exists()) {
            testroot.delete(true);
        }

        final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS");
        if (testrootenamed.exists()) {
            testrootenamed.delete(true);
        }

    }

    if (!testroot.exists()) {

        testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testroot.open(Folder.READ_WRITE);

        testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testrootl2.open(Folder.READ_WRITE);

    }

    final Folder inbox = root.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);

    final Message[] msgs = new Message[count];

    for (int i = 0; i < count; i++) {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        msgs[i] = message;

    }

    inbox.appendMessages(msgs);
    testroot.appendMessages(msgs);
    testrootl2.appendMessages(msgs);

    IMAPUtils.close(inbox);
    IMAPUtils.close(testrootl2);
    IMAPUtils.close(testroot);
    IMAPUtils.close(store);

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

    }