Java Code Examples for javax.mail.Folder#getMessages()
The following examples show how to use
javax.mail.Folder#getMessages() .
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: GreenMailServer.java From micro-integrator with Apache License 2.0 | 7 votes |
/** * 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 2
Source File: Email.java From smslib-v3 with Apache License 2.0 | 6 votes |
@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; }
Example 3
Source File: AbstractIMAPRiverUnitTest.java From elasticsearch-imap with Apache License 2.0 | 6 votes |
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 4
Source File: MxPopTest.java From mireka with Apache License 2.0 | 6 votes |
private void retrieveMail() throws NoSuchProviderException, MessagingException, IOException { Properties properties = new Properties(); Session session = Session.getInstance(properties); Store store = session.getStore(new URLName("pop3://john:secret@localhost:" + 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(); }
Example 5
Source File: MailReader.java From development with Apache License 2.0 | 6 votes |
/** * 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 6
Source File: EmailUtil.java From product-es with Apache License 2.0 | 6 votes |
/** * 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 7
Source File: GreenMailServer.java From micro-integrator with Apache License 2.0 | 6 votes |
/** * 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 8
Source File: MailReceiver.java From tmxeditor8 with GNU General Public License v2.0 | 5 votes |
/** * 接收邮件. * @param expunge * 邮件是否删除 * @return List<Message> * 收到的邮件集合 * @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; }
Example 9
Source File: MalinatorUtil.java From qaf with MIT License | 5 votes |
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(); }
Example 10
Source File: FolderCrawler.java From mnIMAPSync with Apache License 2.0 | 5 votes |
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 11
Source File: StoreMail.java From java-tutorial with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
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(); }
Example 12
Source File: EmailUtil.java From product-es with Apache License 2.0 | 4 votes |
/** * 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; }
Example 13
Source File: ParallelPollingIMAPMailSource.java From elasticsearch-imap with Apache License 2.0 | 4 votes |
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); } }
Example 14
Source File: EmailUtil.java From product-es with Apache License 2.0 | 4 votes |
/** * 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; }
Example 15
Source File: MailReader.java From development with Apache License 2.0 | 4 votes |
/** * 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 16
Source File: ParallelPollingPOPMailSource.java From elasticsearch-imap with Apache License 2.0 | 4 votes |
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); } }
Example 17
Source File: MockImapClient.java From usergrid with Apache License 2.0 | 4 votes |
public void findContent( Folder folder ) throws MessagingException, IOException { for ( Message m : folder.getMessages() ) { logger.info( "Subject: " + m.getSubject() ); } }
Example 18
Source File: cfMailFolderMessagesData.java From openbd-core with GNU General Public License v3.0 | 4 votes |
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 19
Source File: cfPOP3.java From openbd-core with GNU General Public License v3.0 | 4 votes |
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 20
Source File: cfPOP3.java From openbd-core with GNU General Public License v3.0 | 4 votes |
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() ); } }