javax.mail.Folder Java Examples
The following examples show how to use
javax.mail.Folder.
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 | 9 votes |
/** * 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 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 #3
Source File: MailConnection.java From hop with Apache License 2.0 | 6 votes |
/** * 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 #4
Source File: MailListener.java From Ardulink-1 with Apache License 2.0 | 6 votes |
private static void clear(Folder folder) throws MessagingException { if(folder.exists() && (folder.getType() & Folder.HOLDS_MESSAGES) == Folder.HOLDS_MESSAGES) { int totMessages = folder.getMessageCount(); System.out.println(totMessages + " messages from folder: " + folder.getFullName()); folder.open(Folder.READ_WRITE); Message[] messages = folder.getMessages(); for (int i = 0; i < messages.length; i++) { System.out.println("Deleting message: " + (i+1) + " of " + totMessages); messages[i].setFlag(Flags.Flag.DELETED, true); } folder.close(true); } Folder[] childs = folder.list(); for (int i = 0; i < childs.length; i++) { clear(childs[i]); } }
Example #5
Source File: cfMailFolderData.java From openbd-core with GNU General Public License v3.0 | 6 votes |
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 #6
Source File: MessageParser.java From OA with GNU General Public License v3.0 | 6 votes |
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 #7
Source File: DefaultFolder.java From FairEmail with GNU General Public License v3.0 | 6 votes |
@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 #8
Source File: StoreCopier.java From mnIMAPSync with Apache License 2.0 | 6 votes |
/** * 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 #9
Source File: EMailTestServer.java From syndesis with Apache License 2.0 | 6 votes |
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 #10
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 #11
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 #12
Source File: cfImapConnection.java From openbd-core with GNU General Public License v3.0 | 6 votes |
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 #13
Source File: IMAPMockFolder.java From javamail-mock2 with Apache License 2.0 | 6 votes |
@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 #14
Source File: cfImapConnection.java From openbd-core with GNU General Public License v3.0 | 6 votes |
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 #15
Source File: MailConnection.java From pentaho-kettle with Apache License 2.0 | 6 votes |
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 #16
Source File: ImapSubjectLineTest.java From greenmail with Apache License 2.0 | 6 votes |
private void testSubject(String subject) throws Exception { GreenMailUser user = greenMail.setUser("to1@localhost", "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("to1@localhost", "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 #17
Source File: GreenMailServer.java From product-ei 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 #18
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 #19
Source File: IMAPTestCase.java From javamail-mock2 with Apache License 2.0 | 5 votes |
@Test(expected = MockTestException.class) public void testACLUnsupported() 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("mock_imap"); store.connect("[email protected]", null); final Folder defaultFolder = store.getDefaultFolder(); final Folder test = defaultFolder.getFolder("test"); final IMAPFolder testImap = (IMAPFolder) test; try { testImap.getACL(); } catch (final MessagingException e) { throw new MockTestException(e); } }
Example #20
Source File: FolderProcessor.java From james-project with Apache License 2.0 | 5 votes |
/** * Method open. * * @throws MessagingException */ protected void open() throws MessagingException { int openFlag = Folder.READ_WRITE; if (isOpenReadOnly()) { openFlag = Folder.READ_ONLY; } getFolder().open(openFlag); }
Example #21
Source File: MailService.java From camunda-bpm-mail with Apache License 2.0 | 5 votes |
public Folder ensureOpenFolder(Folder folder) throws MessagingException { ensureConnectedStore(folder.getStore()); if (!folder.isOpen()) { openFolder(folder); } return folder; }
Example #22
Source File: StoreDeleter.java From mnIMAPSync with Apache License 2.0 | 5 votes |
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 File: ElasticsearchStateManager.java From elasticsearch-imap with Apache License 2.0 | 5 votes |
@Override public synchronized State getRiverState(final Folder folder) throws MessagingException { try { waitForCluster(); if (client.admin().indices().prepareExists(index()).execute().actionGet().isExists()) { final GetResponse response = client .prepareGet(index(), RIVERSTATE_TYPE, FOLDERSTATE_ID + "_" + folder.getURLName().toString().hashCode()).execute() .get(); if (!response.isSourceEmpty()) { return mapper.readValue(response.getSourceAsString(), new TypeReference<State>() { }); } } } catch (final Exception ex) { throw new MessagingException("Unable to get river state", ex); } final State rs = new State(); rs.setFolderUrl(folder.getURLName().toString()); // rs.setLastUid(1L); rs.setExists(true); return rs; }
Example #24
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 #25
Source File: imap.java From jbang with MIT License | 5 votes |
@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 #26
Source File: ParallelPollingIMAPMailSource.java From elasticsearch-imap with Apache License 2.0 | 5 votes |
protected void recurseFolders(final Folder folder, final Pattern pattern) throws MessagingException, IOException { if (folder != null) { if (es == null || es.isShutdown() || es.isTerminated() || Thread.currentThread().isInterrupted()) { logger.warn("Stop processing of mails due to mail source is closed"); return; } if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) { if (pattern != null && !pattern.matcher(folder.getFullName()).matches()) { logger.debug("Pattern {} does not match {}", pattern.pattern(), folder.getFullName()); return; } IMAPUtils.open(folder); try { fetch(folder); } finally { IMAPUtils.close(folder); logger.debug("fetch {} done", folder.getFullName()); } } if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) { for (final Folder subfolder : folder.list()) { recurseFolders(subfolder, pattern); } } } }
Example #27
Source File: IMAPTestCase.java From javamail-mock2 with Apache License 2.0 | 5 votes |
@Test // (expected = MockTestException.class) public void testAppendFailMessage() 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(); store.connect("[email protected]", null); final Folder defaultFolder = store.getDefaultFolder(); final Folder inbox = defaultFolder.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); try { inbox.appendMessages(new MimeMessage[] { msg }); } catch (final IllegalStateException e) { // throw new MockTestException(e); } // Assert.fail("Exception expected before this point"); Assert.assertEquals(4, inbox.getMessageCount()); inbox.close(false); }
Example #28
Source File: ParallelPollingPOPMailSource.java From elasticsearch-imap with Apache License 2.0 | 5 votes |
protected void recurseFolders(final Folder folder, final Pattern pattern) throws MessagingException, IOException { if (folder != null) { if (es == null || es.isShutdown() || es.isTerminated() || Thread.currentThread().isInterrupted()) { logger.warn("Stop processing of mails due to mail source is closed"); return; } if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) { if (pattern != null && !pattern.matcher(folder.getFullName()).matches()) { logger.debug("Pattern {} does not match {}", pattern.pattern(), folder.getFullName()); return; } IMAPUtils.open(folder); try { fetch(folder); } finally { IMAPUtils.close(folder); } } if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) { for (final Folder subfolder : folder.list()) { recurseFolders(subfolder, pattern); } } } }
Example #29
Source File: FolderCrawlerTest.java From mnIMAPSync with Apache License 2.0 | 5 votes |
@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 #30
Source File: MimePackage.java From ats-framework with Apache License 2.0 | 5 votes |
/** * 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; }