Java Code Examples for javax.mail.Folder#close()
The following examples show how to use
javax.mail.Folder#close() .
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: SMTPTestCase.java From javamail-mock2 with Apache License 2.0 | 6 votes |
@Test public void test2SendMessage2() throws Exception { final Transport transport = session.getTransport(Providers.getSMTPProvider("makes_no_difference_here", true, true)); final MimeMessage msg = new MimeMessage((Session) null); msg.setSubject("Test 1"); msg.setFrom("[email protected]"); msg.setText("Some text here ..."); msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]")); transport.sendMessage(msg, new Address[] { new InternetAddress("[email protected]") }); final Store store = session.getStore("mock_pop3"); store.connect("[email protected]", null); final Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); Assert.assertEquals(1, inbox.getMessageCount()); Assert.assertNotNull(inbox.getMessage(1)); Assert.assertEquals("Test 1", inbox.getMessage(1).getSubject()); inbox.close(false); }
Example 2
Source File: GreenMailServer.java From product-ei with Apache License 2.0 | 6 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: SMTPTestCase.java From javamail-mock2 with Apache License 2.0 | 6 votes |
@Test public void test3SendMessage() throws Exception { Session.getDefaultInstance(getProperties()); final MimeMessage msg = new MimeMessage((Session) null); msg.setSubject("Test 1"); msg.setFrom("[email protected]"); msg.setText("Some text here ..."); msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]")); Transport.send(msg); final Store store = session.getStore("mock_pop3"); store.connect("[email protected]", null); final Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); Assert.assertEquals(1, inbox.getMessageCount()); Assert.assertNotNull(inbox.getMessage(1)); Assert.assertEquals("Test 1", inbox.getMessage(1).getSubject()); inbox.close(false); }
Example 4
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 5
Source File: cfImapConnection.java From openbd-core with GNU General Public License v3.0 | 6 votes |
public void changeStatus( String folderName, long mailIDs[], Flags.Flag newFlag, boolean value ){ try{ Folder folderToUse = mailStore.getFolder(folderName); folderToUse.open( Folder.READ_WRITE ); Flags f = new Flags(); f.add( newFlag ); Message mlist[]; if ( folderToUse instanceof UIDFolder ) mlist = ((UIDFolder)folderToUse).getMessagesByUID( mailIDs ); else mlist = folderToUse.getMessages( returnToInts(mailIDs) ); for ( int x=0; x < mlist.length; x++ ) mlist[x].setFlags( f, value ); folderToUse.close( true ); setData( "succeeded", cfBooleanData.TRUE ); } catch (Exception E ){ setData( "errortext", new cfStringData( E.getMessage() ) ); setData( "succeeded", cfBooleanData.FALSE ); } }
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: 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 8
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 9
Source File: POP3TestCase.java From javamail-mock2 with Apache License 2.0 | 5 votes |
@Test public void testAddMessages() 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 final Store store = session.getStore(); store.connect("[email protected]", null); final Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); Assert.assertEquals(3, inbox.getMessageCount()); Assert.assertNotNull(inbox.getMessage(1)); inbox.close(true); Assert.assertEquals(3, inbox.getMessageCount()); inbox.open(Folder.READ_ONLY); inbox.getMessage(1).setFlag(Flag.DELETED, true); inbox.close(true); inbox.open(Folder.READ_ONLY); Assert.assertEquals(2, inbox.getMessageCount()); Assert.assertTrue(inbox instanceof POP3Folder); Assert.assertEquals("12", ((POP3Folder) inbox).getUID(inbox.getMessage(1))); inbox.close(true); }
Example 10
Source File: MailUtils.java From scada with MIT License | 5 votes |
/** * �����ʼ� */ public static void receive() throws Exception { // �����ӷ������ĻỰ��Ϣ Properties props = new Properties(); props.setProperty("mail.store.protocol", "pop3"); // Э�� props.setProperty("mail.pop3.port", "110"); // �˿� props.setProperty("mail.pop3.host", "pop3.sina.com"); // pop3������ // ����Sessionʵ������ Session session = Session.getInstance(props); Store store = session.getStore("pop3"); store.connect("[email protected]", "mh899821671104"); // ����ռ��� Folder folder = store.getFolder("INBOX"); /* Folder.READ_ONLY��ֻ��Ȩ�� * Folder.READ_WRITE���ɶ���д���������ʼ���״̬�� */ folder.open(Folder.READ_WRITE); //���ռ��� // ����POP3Э������֪�ʼ���״̬,����getUnreadMessageCount�õ������ռ�����ʼ����� System.out.println("δ���ʼ���: " + folder.getUnreadMessageCount()); // ����POP3Э������֪�ʼ���״̬,��������õ��Ľ��ʼ�ն���Ϊ0 System.out.println("ɾ���ʼ���: " + folder.getDeletedMessageCount()); System.out.println("���ʼ�: " + folder.getNewMessageCount()); // ����ռ����е��ʼ����� System.out.println("�ʼ�����: " + folder.getMessageCount()); // �õ��ռ����е������ʼ�,������ Message[] messages = folder.getMessages(); parseMessage(messages); //�ͷ���Դ folder.close(true); store.close(); }
Example 11
Source File: MailReceiver.java From tmxeditor8 with GNU General Public License v2.0 | 5 votes |
/** * 释放资源. * @throws MessagingException * the messaging exception */ public void releaseResource() throws MessagingException { for (Folder folder : folderList) { folder.close(true); } if (store != null) { store.close(); } }
Example 12
Source File: MailReceiverUtils.java From codenvy with Eclipse Public License 1.0 | 5 votes |
/** * check Folder and Store objects from current test email box and close this * * @param folder the current mail folder that should be closed * @param store the current mail store that should be closed * @throws MessagingException */ private void closeStoreAndFolder(Folder folder, Store store) throws MessagingException { if (folder != null) { folder.close(true); } if (store != null) { store.close(); } }
Example 13
Source File: PopMailImporter.java From mireka with Apache License 2.0 | 5 votes |
private void importMails(GlobalUser user) throws MessagingException { logger.debug("Importing mail for " + user.getUsernameObject()); Properties properties = new Properties(); Session session = Session.getInstance(properties); Store store = session.getStore(new URLName("pop3://" + user.getUsernameObject() + ":" + user.getPassword() + "@" + remoteHost + ":" + +remotePort + "/INBOX")); store.connect(); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); Message[] messages = folder.getMessages(); int cSuccessfulMails = 0; // user name currently equals with the maildrop name, but this is // not necessarily true in general. String maildropName = user.getUsernameObject().toString(); for (Message message : messages) { try { importMail(maildropName, message); message.setFlag(Flags.Flag.DELETED, true); cSuccessfulMails++; } catch (Exception e) { logger.error("Importing a mail for " + user.getUsernameObject() + " failed", e); } } folder.close(true); store.close(); totalMailCount += cSuccessfulMails; if (cSuccessfulMails > 0) totalUsersWithAtLeastOneMail++; logger.debug(cSuccessfulMails + " mails were imported for " + user.getUsernameObject()); }
Example 14
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 15
Source File: cfPOP3.java From openbd-core with GNU General Public License v3.0 | 4 votes |
private static void closeFolder( Folder popFolder ) { try{ if ( popFolder != null ) popFolder.close( true ); }catch(Exception ignoreE){} }
Example 16
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 17
Source File: MailReader.java From development with Apache License 2.0 | 4 votes |
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}; }
Example 18
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 19
Source File: DefaultReceiveEmailProvider.java From xframium-java with GNU General Public License v3.0 | 4 votes |
public MessageWrapper _getEmail( String hostName, MessageFilter[] messageFilters, Map<String, String> propertyMap ) { Properties mailProps = new Properties(); mailProps.putAll( propertyMap ); List<Message> messageList = new ArrayList<Message>( 10 ); MessageWrapper messageWrapper = null; try { Session emailSession = Session.getDefaultInstance( mailProps ); Store store = emailSession.getStore( propertyMap.get( PROTOCOL ) ); store.connect( hostName, propertyMap.get( USER_NAME ), propertyMap.get( PASSWORD ) ); Folder emailFolder = store.getFolder( propertyMap.get( FOLDER_NAME ) != null ? propertyMap.get( FOLDER_NAME ) : DEFAULT_FOLDER_NAME ); emailFolder.open( Folder.READ_WRITE ); Message[] messages = emailFolder.getMessages(); int messageCount = emailFolder.getMessageCount(); if ( messageCount > MAX_MESSAGES ) messageCount = MAX_MESSAGES; if ( log.isInfoEnabled() ) log.info( "Processing " + messageCount + " messages" ); for ( int i = 0; i < messageCount; i++ ) { if ( applyFilters( messages[i], messageFilters ) ) { messageList.add( messages[i] ); } } if ( messageList.size() == 0 ) throw new ScriptException( "Failed to find any email messages that met the criteria" ); Collections.sort( messageList, new DateComparator() ); String messageContent = null; String contentType = messageList.get( 0 ).getContentType(); if ( contentType.startsWith( "text/" ) ) messageContent = messageList.get( 0 ).getContent().toString(); else if ( messageList.get( 0 ).isMimeType( "multipart/*" ) ) messageContent = getTextFromMimeMultipart( (MimeMultipart) messageList.get( 0 ).getContent() ); else messageContent = messageList.get( 0 ).getContent().getClass().getName(); messageWrapper = new MessageWrapper( messageList.size(), messageList.get( 0 ).getFrom()[0].toString(), messageList.get( 0 ).getSubject(), messageContent, contentType ); emailFolder.close( false ); store.close(); } catch ( Exception e ) { e.printStackTrace(); throw new ScriptException( "Failed to find email" ); } return messageWrapper; }
Example 20
Source File: JavaMailContainer.java From scipio-erp with Apache License 2.0 | 4 votes |
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); }