javax.mail.Folder#getMessages ( )源码实例Demo

下面列出了javax.mail.Folder#getMessages ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: micro-integrator   文件: GreenMailServer.java
/**
 * 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();
        }
    }
}
 
源代码2 项目: micro-integrator   文件: GreenMailServer.java
/**
 * 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;
}
 
源代码3 项目: product-es   文件: EmailUtil.java
/**
 * 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();
}
 
源代码4 项目: smslib-v3   文件: Email.java
@Override
public Collection<OutboundMessage> getMessagesToSend() throws Exception
{
	List<OutboundMessage> retValue = new ArrayList<OutboundMessage>();
	Store s = this.mailSession.getStore();
	s.connect();
	Folder inbox = s.getFolder(getProperty("mailbox_name", "INBOX"));
	inbox.open(Folder.READ_WRITE);
	for (Message m : inbox.getMessages())
	{
		OutboundMessage om = new OutboundMessage(m.getSubject(), m.getContent().toString());
		om.setFrom(m.getFrom().toString());
		om.setDate(m.getReceivedDate());
		retValue.add(om);
		// Delete message from inbox
		m.setFlag(Flags.Flag.DELETED, true);
	}
	inbox.close(true);
	s.close();
	return retValue;
}
 
源代码5 项目: development   文件: MailReader.java
/**
 * 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);

}
 
源代码6 项目: mireka   文件: MxPopTest.java
private void retrieveMail() throws NoSuchProviderException,
        MessagingException, IOException {
    Properties properties = new Properties();
    Session session = Session.getInstance(properties);
    Store store =
            session.getStore(new URLName("pop3://john:[email protected]:"
                    + PORT_POP + "/INBOX"));
    store.connect();
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    Message[] messages = folder.getMessages();
    assertEquals(1, messages.length);
    Message message = messages[0];
    assertEquals("Hello World!\r\n", message.getContent());
    message.setFlag(Flags.Flag.DELETED, true);
    folder.close(true);
    store.close();
}
 
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();

}
 
源代码8 项目: java-tutorial   文件: StoreMail.java
public static void main(String[] args) throws Exception {

		// 创建一个有具体连接信息的Properties对象
		Properties prop = new Properties();
		prop.setProperty("mail.debug", "true");
		prop.setProperty("mail.store.protocol", "pop3");
		prop.setProperty("mail.pop3.host", MAIL_SERVER_HOST);

		// 1、创建session
		Session session = Session.getInstance(prop);

		// 2、通过session得到Store对象
		Store store = session.getStore();

		// 3、连上邮件服务器
		store.connect(MAIL_SERVER_HOST, USER, PASSWORD);

		// 4、获得邮箱内的邮件夹
		Folder folder = store.getFolder("inbox");
		folder.open(Folder.READ_ONLY);

		// 获得邮件夹Folder内的所有邮件Message对象
		Message[] messages = folder.getMessages();
		for (int i = 0; i < messages.length; i++) {
			String subject = messages[i].getSubject();
			String from = (messages[i].getFrom()[0]).toString();
			System.out.println("第 " + (i + 1) + "封邮件的主题:" + subject);
			System.out.println("第 " + (i + 1) + "封邮件的发件人地址:" + from);
		}

		// 5、关闭
		folder.close(false);
		store.close();
	}
 
源代码9 项目: mnIMAPSync   文件: FolderCrawler.java
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);
}
 
源代码10 项目: tmxeditor8   文件: MailReceiver.java
/**
 * 接收邮件.
 * @param expunge
 *            	邮件是否删除
 * @return List&lt;Message&gt;
 * 				收到的邮件集合
 * @throws MessagingException
 *             the messaging exception
 */
public List<Message> receive(boolean expunge) throws MessagingException {
	List<Message> result = new ArrayList<Message>();
	store = session.getStore();
	store.connect();
	Folder folder = store.getFolder("INBOX");
	folder.open(Folder.READ_WRITE);
	for (Message message : folder.getMessages()) {
		result.add(message);
		//设置邮件的 DELETED 标志
		message.setFlag(Flags.Flag.DELETED, expunge);
	}
	folderList.add(folder);
	return result;
}
 
源代码11 项目: qaf   文件: MalinatorUtil.java
public static void main(String[] args) throws Exception {

		Properties props = new Properties();

		String host = "pop.mailinator.com";
		String username = "x-test-m";
		String password = "mypwdxxx";
		String provider = "pop3";

		Session session = Session.getDefaultInstance(props, null);
		Store store = session.getStore(provider);
		store.connect(host, username, password);

		Folder inbox = store.getFolder("INBOX");
		if (inbox == null) {
			System.out.println("No INBOX");
			System.exit(1);
		}
		inbox.open(Folder.READ_ONLY);

		Message[] messages = inbox.getMessages();
		for (int i = 0; i < messages.length; i++) {
			System.out.println("Message " + (i + 1));
			messages[i].writeTo(System.out);
		}
		inbox.close(false);
		store.close();

	}
 
源代码12 项目: product-es   文件: EmailUtil.java
/**
 * This method read e-mails from Gmail inbox and find whether the notification of particular type is found.
 *
 * @param   notificationType    Notification types supported by publisher and store.
 * @return  whether email is found for particular type.
 * @throws  Exception
 */
public static boolean readGmailInboxForNotification(String notificationType) throws Exception {
    boolean isNotificationMailAvailable = false;
    long waitTime = 10000;
    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 inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Thread.sleep(waitTime);

    long startTime = System.currentTimeMillis();
    long endTime = 0;
    int count = 1;
    while (endTime - startTime < 180000 && !isNotificationMailAvailable) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if(!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());

                    if (message.getSubject().contains(notificationType)) {
                        isNotificationMailAvailable = true;

                    }
                    // Optional : deleting the  mail
                    message.setFlag(Flags.Flag.DELETED, true);
                } catch (MessageRemovedException e) {
                    log.error("Could not read the message subject. Message is removed from inbox");
                }
            }

        }
        endTime = System.currentTimeMillis();
        Thread.sleep(waitTime);
        endTime += count*waitTime;
        count++;
    }
    inbox.close(true);
    store.close();
    return isNotificationMailAvailable;
}
 
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);
        }

    }
 
源代码14 项目: product-es   文件: EmailUtil.java
/**
 * This method read verification e-mail from Gmail inbox and returns the verification URL.
 *
 * @return  verification redirection URL.
 * @throws  Exception
 */
public static String readGmailInboxForVerification() throws Exception {
    boolean isEmailVerified = false;
    long waitTime = 10000;
    String pointBrowserURL = "";
    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 inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Thread.sleep(waitTime);
    long startTime = System.currentTimeMillis();
    long endTime = 0;
    int count = 1;
    while (endTime - startTime < 180000 && !isEmailVerified) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if (!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());
                    if (message.getSubject().contains("EmailVerification")) {
                        pointBrowserURL = getBodyFromMessage(message);
                        isEmailVerified = true;
                    }

                    // Optional : deleting the mail
                    message.setFlag(Flags.Flag.DELETED, true);
                } catch (MessageRemovedException e){
                    log.error("Could not read the message subject. Message is removed from inbox");
                }
            }
        }
        endTime = System.currentTimeMillis();
        Thread.sleep(waitTime);
        endTime += count*waitTime;
        count++;
    }
    inbox.close(true);
    store.close();
    return pointBrowserURL;
}
 
源代码15 项目: development   文件: MailReader.java
/**
 * 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 "";
}
 
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);
        }

    }
 
源代码17 项目: usergrid   文件: MockImapClient.java
public void findContent( Folder folder ) throws MessagingException, IOException {
    for ( Message m : folder.getMessages() ) {
        logger.info( "Subject: " + m.getSubject() );
    }
}
 
源代码18 项目: openbd-core   文件: cfMailFolderMessagesData.java
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;
}
 
源代码19 项目: openbd-core   文件: cfPOP3.java
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 );
	}
 
源代码20 项目: openbd-core   文件: cfPOP3.java
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() );
  }

}