/** * 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); }
/** * Adds required headers to fetch profile * * @param fetchProfile * @return */ public static final FetchProfile addHeaders(FetchProfile fetchProfile) { fetchProfile.add(FetchProfile.Item.ENVELOPE); //Some servers respond to get a header request with a partial response of the header //when hMailServer is fetched for To or From, it returns only the first entry, //so when compared with other server versions, e-mails appear to be different. fetchProfile.add(IMAPFolder.FetchProfileItem.HEADERS); //If using the header consructor add this for performance. // for (String header : new String[]{ // MessageId.HEADER_MESSAGE_ID, // MessageId.HEADER_SUBJECT, // MessageId.HEADER_FROM, // MessageId.HEADER_TO}) { // fetchProfile.add(header.toUpperCase()); // } return fetchProfile; }
/** * Get the model for the messages in this folder. */ public Object getMessageListModel() { if (_holdsMessages) { if (_messageListModel == null) { FetchProfile fetchProfile = new FetchProfile(); fetchProfile.add(FetchProfile.Item.ENVELOPE); fetchProfile.add(FetchProfile.Item.FLAGS); _messageListModel = new MessageDataModel(_folder, fetchProfile, _MESSAGE_LOAD_BLOCK_SIZE); } return _messageListModel; } else { return null; } }
/** * ��ȡ������������Message */ private javax.mail.Message[] getMessages() throws Exception { Properties props = System.getProperties(); if (ssl) { handleSSL(props); host = host.replace("pop3", "pop"); } Session session = Session.getDefaultInstance(props, null); store = session.getStore("pop3"); store.connect(host, username, password); folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); javax.mail.Message[] msgs = folder.getMessages(); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(msgs, fp); return msgs; }
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); }
/** * 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 ""; }
public String[] readPassAndKeyFromEmail(boolean delete, String userName) throws MessagingException { // Download message headers from server. int retries = 0; String userPass = null; String userKey = null; while (retries < 40 && userPass == null) { // 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(MAIL_SUBJECT_USER_ACCOUNT_CREATED_EN)) { String content = getMessageContent(message); String userNameFromEmail = readInformationFromGivenMail(MAIL_BODY_USERNAME_PATTERN_EN, content); if (userName.equals(userNameFromEmail)) { userKey = readInformationFromGivenMail(MAIL_BODY_USERKEY_PATTERN_EN, content); userPass = readInformationFromGivenMail(MAIL_BODY_PASSWORD_PATTERN_EN, content); if (delete) { message.setFlag(Flag.DELETED, true); } break; } } } folder.close(true); try { Thread.sleep(1000); } catch (InterruptedException e) { // ignored } retries++; } return new String[] {userKey, userPass}; }
public MessageDataModel( Folder folder, FetchProfile fetchProfile, int blockSize) { setWrappedData(folder); _blockSize = blockSize; _fetchProfile = fetchProfile; }
@Override public void fetch(Message[] msgs, FetchProfile fp) throws RuntimeMessagingException { try { delegate.fetch(msgs, fp); } catch (MessagingException e) { throw new RuntimeMessagingException(e); } }
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; }
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 ); }
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() ); } }
public void run() { long deleted = 0l, skipped = 0l; try { final Folder targetFolder = storeDeleter.getTargetStore().getFolder(targetFolderName); //Opens a new connection per Thread targetFolder.open(Folder.READ_WRITE); final Message[] targetMessages = targetFolder.getMessages(start, end); targetFolder.fetch(targetMessages, MessageId.addHeaders(new FetchProfile())); for (Message message : targetMessages) { try { final MessageId id = new MessageId((IMAPMessage) message); if (!sourceFolderMessages.contains(id)) { message.setFlag(Flags.Flag.DELETED, true); deleted++; } else { skipped++; } } catch (MessageId.MessageIdException ex) { //Usually messages that ran into this exception are spammy, so we skip them. skipped++; } } //Close folder and expunge flagged messages //Expunge only if folder is read write if (targetFolder.getMode() == Folder.READ_ONLY) { targetFolder.close(false); } else { targetFolder.close(expunge); } } catch (MessagingException messagingException) { Logger.getLogger(StoreIndex.class.getName()).log(Level.SEVERE, null, messagingException); } storeDeleter.updatedMessagesDeletedCount(deleted); storeDeleter.updateMessagesSkippedCount(skipped); }
public void run() { long indexedMessages = 0l, 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 (storeIndex.hasCrawlException()) { return; } try { final MessageId messageId = new MessageId((IMAPMessage) message); if (storeIndex.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) { storeIndex.getCrawlExceptions().add(messagingException); } storeIndex.updatedIndexedMessageCount(indexedMessages); storeIndex.updatedSkippedMessageCount(skippedMessages); }
@Override public void fetch(final Message[] msgs, final FetchProfile fp) throws MessagingException { // just do nothing }
@Override public synchronized void fetch(final Message[] msgs, final FetchProfile fp) throws MessagingException { abortIdle(); // do nothing more }
private void readMessagesFolder(Folder folder) throws MessagingException, IOException, SearchLibException { folder.open(Folder.READ_ONLY); String folderFullName = folder.getFullName(); try { int max = folder.getMessageCount(); int i = 0; final int buffer = item.getBufferSize(); while (i < max && !thread.isAborted()) { thread.setStatusInfo(CrawlStatus.CRAWL); int end = i + buffer; if (end > max) end = max; Message[] messages = folder.getMessages(i + 1, end); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); folder.fetch(messages, fp); for (Message message : messages) { if (thread.isAborted()) break; i++; String messageId = getMessageId(folder, message); if (StringUtils.isEmpty(messageId)) continue; if (thread.isAlreadyIndexed(messageId)) { thread.incIgnored(); continue; } IndexDocument crawlIndexDocument = new IndexDocument( item.getLang()); IndexDocument parserIndexDocument = new IndexDocument( item.getLang()); crawlIndexDocument.addString( MailboxFieldEnum.folder.name(), folderFullName); try { readMessage(crawlIndexDocument, parserIndexDocument, folder, message, messageId); thread.addDocument(crawlIndexDocument, parserIndexDocument); } catch (Exception e) { Logging.warn(e); thread.incError(); } } } } finally { folder.close(false); } }