Java Code Examples for javax.mail.Folder

The following examples show how to use javax.mail.Folder. 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: micro-integrator   Source File: GreenMailServer.java    License: Apache License 2.0 7 votes vote down vote up
/**
 * Check mail folder for an email using subject.
 *
 * @param emailSubject Email subject
 * @param folder       mail folder to check for an email
 * @param protocol     protocol used to connect to the server
 * @return whether mail received or not
 * @throws MessagingException if we're unable to connect to the store
 */
private static boolean isMailReceivedBySubject(String emailSubject, String folder, String protocol,
                                               GreenMailUser user) throws MessagingException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection(user, protocol);
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the Email with Subject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
    } finally {
        if (store != null) {
            store.close();
        }
    }
    return emailReceived;
}
 
Example 2
Source Project: micro-integrator   Source File: GreenMailServer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delete all emails in the inbox.
 *
 * @param protocol protocol used to connect to the server
 * @throws MessagingException if we're unable to connect to the store
 */
public static void deleteAllEmails(String protocol, GreenMailUser user) throws MessagingException {
    Folder inbox = null;
    Store store = getConnection(user, protocol);
    try {
        inbox = store.getFolder(EMAIL_INBOX);
        inbox.open(Folder.READ_WRITE);
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            message.setFlag(Flags.Flag.DELETED, true);
            log.info("Deleted email Subject : " + message.getSubject());
        }
    } finally {
        if (inbox != null) {
            inbox.close(true);
        }
        if (store != null) {
            store.close();
        }
    }
}
 
Example 3
Source Project: openbd-core   Source File: cfMailFolderData.java    License: GNU General Public License v3.0 6 votes vote down vote up
public cfQueryResultData listAllFolders( cfImapConnection imapConnection) throws cfmRunTimeException {
	cfQueryResultData query	= new cfQueryResultData( new String[]{"fullname","name","totalmessages","unread","new"},"CFIMAP" );						
	
	try{
		Folder	folderToList;
		folderToList = imapConnection.mailStore.getDefaultFolder();

		if ( (folderToList.getType() & Folder.HOLDS_FOLDERS) != 0){
			Folder[] folderArray = folderToList.list("*");
			query.addRow( folderArray.length );				
			
			for (int i = 0; i < folderArray.length; i++)
				folderRow( query, i+1, folderArray[i] );
		}

	}catch(Exception E){}
	
	return query;
}
 
Example 4
Source Project: Ardulink-1   Source File: MailListener.java    License: 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 Project: hop   Source File: MailConnection.java    License: 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 6
Source Project: FairEmail   Source File: DefaultFolder.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
   public synchronized Folder[] listSubscribed(final String pattern)
			throws MessagingException {
ListInfo[] li = null;

li = (ListInfo[])doCommand(new ProtocolCommand() {
    @Override
    public Object doCommand(IMAPProtocol p) throws ProtocolException {
	return p.lsub("", pattern);
    }
});

if (li == null)
    return new Folder[0];

IMAPFolder[] folders = new IMAPFolder[li.length];
for (int i = 0; i < folders.length; i++)
    folders[i] = ((IMAPStore)store).newIMAPFolder(li[i]);
return folders;
   }
 
Example 7
Source Project: mnIMAPSync   Source File: StoreCopier.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create folders in the target server recursively from the source.
 *
 * It also indexes the source store folders if we want to delete target folders that no longer
 * exist
 */
private void copySourceFolder(Folder folder) throws MessagingException {
    final String sourceFolderName = folder.getFullName();
    final String targetFolderName = sourceFolderNameToTarget(sourceFolderName, sourceIndex,
        targetIndex);
    //Index for delete after copy (if necessary)
    if (sourceIndex != null) {
        sourceIndex.addFolder(sourceFolderName);
    }
    //Copy folder
    if (!targetIndex.containsFolder(targetFolderName)) {
        if (!targetStore.getFolder(targetFolderName).create(folder.getType())) {
            throw new MessagingException(String.format(
                    "Couldn't create folder: %s in target server.", sourceFolderName));
        }
        incrementFoldersCopiedCount();
    } else {
        incrementFoldersSkippedCount();
    }
    //Folder recursion. Get all children
    if ((folder.getType() & Folder.HOLDS_FOLDERS) == Folder.HOLDS_FOLDERS) {
        for (Folder child : folder.list()) {
            copySourceFolder(child);
        }
    }
}
 
Example 8
Source Project: syndesis   Source File: EMailTestServer.java    License: 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 9
Source Project: product-es   Source File: EmailUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method delete all the sent mails. Can be used after a particular test class
 *
 * @throws  MessagingException
 * @throws  IOException
 */
public static void deleteSentMails() throws MessagingException, IOException {
    Properties props = new Properties();
    props.load(new FileInputStream(new File(
            TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator
                    + "smtp.properties")));
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString());

    Folder sentMail = store.getFolder("[Gmail]/Sent Mail");
    sentMail.open(Folder.READ_WRITE);
    Message[] messages =sentMail.getMessages();
    Flags deleted = new Flags(Flags.Flag.DELETED);
    sentMail.setFlags(messages,deleted,true);
    sentMail.close(true);
    store.close();
}
 
Example 10
Source Project: OA   Source File: MessageParser.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void parse(Message... messages) {
	if (messages == null || messages.length == 0) {
		System.out.println("没有任何邮件");
	} else {
		for (Message m : messages) {
			parse(m);
		}
		// 最后关闭连接
		if (messages[0] != null) {
			Folder folder = messages[0].getFolder();
			if (folder != null) {
				try {
					Store store = folder.getStore();
					folder.close(false);// 参数false表示对邮件的修改不传送到服务器上
					if (store != null) {
						store.close();
					}
				} catch (MessagingException e) {
					// ignore
				}
			}
		}
	}

}
 
Example 11
Source Project: greenmail   Source File: ImapSubjectLineTest.java    License: Apache License 2.0 6 votes vote down vote up
private void testSubject(String subject) throws Exception {
    GreenMailUser user = greenMail.setUser("[email protected]", "pwd");
    assertNotNull(greenMail.getImap());

    MailFolder folder = greenMail.getManagers().getImapHostManager().getFolder(user, "INBOX");
    storeSearchTestMessages(greenMail.getImap().createSession(), folder, subject);

    greenMail.waitForIncomingEmail(1);

    final Store store = greenMail.getImap().createStore();
    store.connect("[email protected]", "pwd");
    try {
        Folder imapFolder = store.getFolder("INBOX");
        imapFolder.open(Folder.READ_ONLY);

        Message[] imapMessages = imapFolder.getMessages();
        assertTrue(null != imapMessages && imapMessages.length == 1);
        Message imapMessage = imapMessages[0];
        assertEquals(subject.replaceAll("\\s+",""), imapMessage.getSubject().replaceAll("\\s+",""));
    } finally {
        store.close();
    }
}
 
Example 12
protected void deleteMailsFromUserMailbox(final Properties props, final String folderName, final int start, final int deleteCount,
        final String user, final String password) throws MessagingException {
    final Store store = Session.getInstance(props).getStore();

    store.connect(user, password);
    checkStoreForTestConnection(store);
    final Folder f = store.getFolder(folderName);
    f.open(Folder.READ_WRITE);

    final int msgCount = f.getMessageCount();

    final Message[] m = deleteCount == -1 ? f.getMessages() : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1));
    int d = 0;

    for (final Message message : m) {
        message.setFlag(Flag.DELETED, true);
        logger.info("Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject());
        d++;
    }

    f.close(true);
    logger.info("Deleted " + d + " messages");
    store.close();

}
 
Example 13
Source Project: openbd-core   Source File: cfImapConnection.java    License: 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 14
Source Project: javamail-mock2   Source File: IMAPMockFolder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public synchronized AppendUID[] copyUIDMessages(final Message[] msgs, final Folder folder) throws MessagingException {

    abortIdle();
    checkExists();
    checkOpened();
    if (msgs == null || folder == null || msgs.length == 0) {
        return null;
    }

    final AppendUID[] uids = new AppendUID[msgs.length];

    int i = 0;
    for (final Message m : msgs) {
        final MockMessage mockMessage = (MockMessage) mailboxFolder.add((MimeMessage) m);
        uids[i++] = new AppendUID(mailboxFolder.getUidValidity(), mockMessage.getMockid());
    }

    logger.debug("Copied " + msgs.length + " to " + getFullName());

    return uids;
}
 
Example 15
Source Project: openbd-core   Source File: cfImapConnection.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void copyMessages( String destFolder, Message msg ){
  try{
  
    Folder folderToUse = mailStore.getFolder(destFolder);
    folderToUse.open( Folder.READ_WRITE );

    Message[] list  = new Message[1];
    list[0] = msg;
    
    folderToUse.appendMessages( list );
    folderToUse.close(false);
    setData( "succeeded", 	cfBooleanData.TRUE );
    
 	lastUsed	= System.currentTimeMillis();
  
  } catch (Exception E ){
    setData( "errortext", 	new cfStringData( E.getMessage() ) );
    setData( "succeeded", 	cfBooleanData.FALSE );
  }
}
 
Example 16
Source Project: pentaho-kettle   Source File: MailConnection.java    License: Apache License 2.0 6 votes vote down vote up
private HashSet<String> returnSubfolders( Folder folder ) throws KettleException {
  HashSet<String> list = new HashSet<String>();
  try {
    if ( ( folder.getType() & Folder.HOLDS_FOLDERS ) != 0 ) {
      Folder[] f = folder.list();
      for ( int i = 0; i < f.length; i++ ) {
        // Search for sub folders
        if ( ( f[i].getType() & Folder.HOLDS_FOLDERS ) != 0 ) {
          list.add( f[i].getFullName() );
          list.addAll( returnSubfolders( f[i] ) );
        }
      }
    }
  } catch ( MessagingException m ) {
    throw new KettleException( m );
  }
  return list;
}
 
Example 17
Source Project: product-ei   Source File: GreenMailServer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check whether email received by reading the emails.
 *
 * @param protocol to connect to the store
 * @param user whose mail store should be connected
 * @param subject the subject of the mail to search
 * @return
 * @throws MessagingException when unable to connect to the store
 */
public static boolean isMailReceived(String protocol, GreenMailUser user, String subject)
        throws MessagingException {
    Store store = getConnection(user, protocol);
    Folder folder = store.getFolder(EMAIL_INBOX);
    folder.open(Folder.READ_ONLY);
    boolean isReceived = false;
    Message[] messages = folder.getMessages();
    for (Message message : messages) {
        if (message.getSubject().contains(subject)) {
            log.info("Found the Email with Subject : " + subject);
            isReceived = true;
            break;
        }
    }
    return isReceived;
}
 
Example 18
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 19
Source Project: mnIMAPSync   Source File: StoreCrawler.java    License: 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 20
Source Project: mnIMAPSync   Source File: FolderCrawlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
  imapStore = Mockito.mock(IMAPStore.class);
  folder = Mockito.mock(Folder.class);
  doReturn(folder).when(imapStore).getFolder(anyString());
  index = Mockito.spy(new Index());
}
 
Example 21
Source Project: jbang   Source File: imap.java    License: MIT License 5 votes vote down vote up
@Override
public Integer call() throws Exception {
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect(host, username, password);
    //System.out.println(store);

    Folder f = store.getFolder(folder);
    System.out.println(f.getName() + ":" + f.getUnreadMessageCount());

    return f.getUnreadMessageCount();
}
 
Example 22
Source Project: mnIMAPSync   Source File: StoreDeleter.java    License: 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 23
Source Project: hop   Source File: MailConnection.java    License: Apache License 2.0 5 votes vote down vote up
private Folder getRecursiveFolder( String foldername ) throws MessagingException {
  Folder dfolder;
  String[] folderparts = foldername.split( "/" );
  dfolder = this.getStore().getDefaultFolder();
  // Open destination folder
  for ( int i = 0; i < folderparts.length; i++ ) {
    dfolder = dfolder.getFolder( folderparts[ i ] );
  }
  return dfolder;
}
 
Example 24
Source Project: mail-importer   Source File: JavaxMailFolder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean renameTo(Folder f) throws RuntimeMessagingException {
  try {
    return delegate.renameTo(f);
  } catch (MessagingException e) {
    throw new RuntimeMessagingException(e);
  }
}
 
Example 25
Source Project: mail-importer   Source File: JavaxMailStorage.java    License: 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 26
Source Project: hop   Source File: MailConnectionTest.java    License: Apache License 2.0 5 votes vote down vote up
public Mconn( ILogChannel log ) throws HopException, MessagingException {
  super( log, MailConnectionMeta.PROTOCOL_IMAP, "junit", 0, "junit", "junit", false, false, "junit" );

  store = Mockito.mock( Store.class );

  inbox = Mockito.mock( Folder.class );
  a = Mockito.mock( Folder.class );
  b = Mockito.mock( Folder.class );
  c = Mockito.mock( Folder.class );

  when( a.getFullName() ).thenReturn( "A" );
  when( b.getFullName() ).thenReturn( "B" );
  when( c.getFullName() ).thenReturn( "C" );

  when( a.exists() ).thenReturn( true );
  when( b.exists() ).thenReturn( true );
  when( c.exists() ).thenReturn( cCreated );
  when( c.create( Mockito.anyInt() ) ).thenAnswer( new Answer<Boolean>() {
    @Override
    public Boolean answer( InvocationOnMock invocation ) throws Throwable {
      Object arg0 = invocation.getArguments()[ 0 ];
      mode = Integer.class.cast( arg0 );
      cCreated = true;
      return true;
    }
  } );

  when( inbox.getFolder( "a" ) ).thenReturn( a );
  when( a.getFolder( "b" ) ).thenReturn( b );
  when( b.getFolder( "c" ) ).thenReturn( c );

  when( store.getDefaultFolder() ).thenReturn( inbox );

}
 
Example 27
Source Project: FairEmail   Source File: EmailService.java    License: GNU General Public License v3.0 5 votes vote down vote up
List<EntityFolder> getFolders() throws MessagingException {
    List<EntityFolder> folders = new ArrayList<>();

    for (Folder ifolder : getStore().getDefaultFolder().list("*")) {
        String fullName = ifolder.getFullName();
        String[] attrs = ((IMAPFolder) ifolder).getAttributes();
        String type = EntityFolder.getType(attrs, fullName, true);
        Log.i(fullName + " attrs=" + TextUtils.join(" ", attrs) + " type=" + type);

        if (type != null)
            folders.add(new EntityFolder(fullName, type));
    }

    EntityFolder.guessTypes(folders, getStore().getDefaultFolder().getSeparator());

    boolean inbox = false;
    boolean drafts = false;
    for (EntityFolder folder : folders)
        if (EntityFolder.INBOX.equals(folder.type))
            inbox = true;
        else if (EntityFolder.DRAFTS.equals(folder.type))
            drafts = true;

    if (!inbox || !drafts)
        return null;

    return folders;
}
 
Example 28
Source Project: javamail-mock2   Source File: IMAPTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAppendMessage() 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(Providers.getIMAPProvider("makes_no_difference_here", true, true));
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();
    final Folder inbox = defaultFolder.getFolder("INBOX");

    inbox.open(Folder.READ_WRITE);

    inbox.appendMessages(new MimeMessage[] { msg });

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

    inbox.close(true);

}
 
Example 29
Source Project: NoraUi   Source File: MailSteps.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Valid activation email.
 *
 * @param mailHost
 *            example: imap.gmail.com
 * @param mailUser
 *            login of mail box
 * @param mailPassword
 *            password of mail box
 * @param senderMail
 *            sender of mail box
 * @param subjectMail
 *            subject of mail box
 * @param firstCssQuery
 *            the first matching element
 * @param conditions
 *            list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
 * @throws TechnicalException
 *             is throws if you have a technical error (format, configuration, datas, ...) in NoraUi.
 *             Exception with message and with screenshot and with exception if functional error but no screenshot and no exception if technical error.
 * @throws FailureException
 *             if the scenario encounters a functional error
 */
@Experimental(name = "validActivationEmail")
@RetryOnFailure(attempts = 3, delay = 60)
@Conditioned
@Et("Je valide le mail d'activation {string}(\\?)")
@And("I valid activation email {string}(\\?)")
public void validActivationEmail(String mailHost, String mailUser, String mailPassword, String senderMail, String subjectMail, String firstCssQuery, List<GherkinStepCondition> conditions)
        throws FailureException, TechnicalException {
    try {
        final Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imap");
        final Session session = Session.getDefaultInstance(props, null);
        final Store store = session.getStore("imaps");
        store.connect(mailHost, mailUser, mailPassword);
        final Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        final SearchTerm filterA = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        final SearchTerm filterB = new FromTerm(new InternetAddress(senderMail));
        final SearchTerm filterC = new SubjectTerm(subjectMail);
        final SearchTerm[] filters = { filterA, filterB, filterC };
        final SearchTerm searchTerm = new AndTerm(filters);
        final Message[] messages = inbox.search(searchTerm);
        for (final Message message : messages) {
            validateActivationLink(subjectMail, firstCssQuery, message);
        }
    } catch (final Exception e) {
        new Result.Failure<>("", Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_MAIL_ACTIVATION), subjectMail), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
    }
}
 
Example 30
Source Project: ats-framework   Source File: MimePackage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reconnects if connection is closed.
 * <b>Note</b>Internal method
 * @return true if store re-connection is performed and this means that close should be closed after the work is done
 * @throws MessagingException
 */
public boolean reconnectStoreIfClosed() throws MessagingException {

    boolean storeReconnected = false;

    // the folder is empty when the message is not loaded from IMAP server, but from a file
    Folder imapFolder = message.getFolder();
    if (imapFolder == null) {
        imapFolder = this.partOfImapFolder;
    } else {
        partOfImapFolder = imapFolder; // keep reference
    }
    if (imapFolder != null) {
        Store store = imapFolder.getStore();
        if (store != null) {
            if (!store.isConnected()) {
                log.debug("Reconnecting store... ");
                store.connect();
                storeReconnected = true;
            }

            // Open folder in read-only mode
            if (!imapFolder.isOpen()) {
                log.debug("Reopening folder " + imapFolder.getFullName()
                          + " in order to get contents of mail message");
                imapFolder.open(Folder.READ_ONLY);
            }
        }
    }
    return storeReconnected;
}