List of usage examples for javax.mail Store getFolder
public abstract Folder getFolder(URLName url) throws MessagingException;
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@Test public void testIdleReconnects() throws Exception { ImapMailReceiver receiver = spy(new ImapMailReceiver("imap:foo")); receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet();/* w ww . ja va2s . co m*/ IMAPFolder folder = mock(IMAPFolder.class); given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER)); given(folder.isOpen()).willReturn(false).willReturn(true); given(folder.exists()).willReturn(true); given(folder.hasNewMessages()).willReturn(true); Field storeField = AbstractMailReceiver.class.getDeclaredField("store"); storeField.setAccessible(true); Store store = mock(Store.class); given(store.isConnected()).willReturn(false); given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder); storeField.set(receiver, store); ImapIdleChannelAdapter adapter = new ImapIdleChannelAdapter(receiver); Log logger = spy(TestUtils.getPropertyValue(adapter, "logger", Log.class)); new DirectFieldAccessor(adapter).setPropertyValue("logger", logger); willDoNothing().given(logger).warn(anyString(), any(Throwable.class)); willAnswer(i -> { i.callRealMethod(); throw new FolderClosedException(folder, "test"); }).given(receiver).waitForNewMessages(); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.initialize(); adapter.setTaskScheduler(taskScheduler); adapter.setReconnectDelay(50); adapter.afterPropertiesSet(); final CountDownLatch latch = new CountDownLatch(3); adapter.setApplicationEventPublisher(e -> { latch.countDown(); }); adapter.start(); assertTrue(latch.await(60, TimeUnit.SECONDS)); verify(store, atLeast(3)).connect(); taskScheduler.shutdown(); }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@SuppressWarnings("resource") @Test/*from w w w.ja va 2 s . c o m*/ public void testInitialIdleDelayWhenRecentIsSupported() throws Exception { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); ImapMailReceiver receiver = new ImapMailReceiver("imap:foo"); receiver = spy(receiver); receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet(); final IMAPFolder folder = mock(IMAPFolder.class); given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.RECENT)); given(folder.isOpen()).willReturn(false).willReturn(true); given(folder.exists()).willReturn(true); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); adapterAccessor.setPropertyValue("mailReceiver", receiver); Field storeField = AbstractMailReceiver.class.getDeclaredField("store"); storeField.setAccessible(true); Store store = mock(Store.class); given(store.isConnected()).willReturn(true); given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder); storeField.set(receiver, store); willAnswer(invocation -> folder).given(receiver).getFolder(); MimeMessage mailMessage = mock(MimeMessage.class); Flags flags = mock(Flags.class); given(mailMessage.getFlags()).willReturn(flags); final Message[] messages = new Message[] { mailMessage }; willAnswer(invocation -> messages).given(receiver).searchForNewMessages(); willAnswer(invocation -> null).given(receiver).fetchMessages(messages); final CountDownLatch idles = new CountDownLatch(2); willAnswer(invocation -> { idles.countDown(); Thread.sleep(5000); return null; }).given(folder).idle(); adapter.start(); /* * Idle takes 5 seconds; since this server supports RECENT, we should * not receive any early messages. */ assertNull(channel.receive(3000)); assertNotNull(channel.receive(5000)); assertTrue(idles.await(5, TimeUnit.SECONDS)); adapter.stop(); context.close(); }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
public void testEightBitMessage() throws Exception { Store lstore = session.getStore(PROTOCOL); lstore.connect(imapServer.getHost(), imapServer.getPort(), ADMIN_USER_NAME, ADMIN_USER_PASSWORD); String folderName = "Alfresco IMAP/" + IMAP_FOLDER_NAME; IMAPFolder lfolder = (IMAPFolder) lstore.getFolder(folderName); lfolder.open(Folder.READ_WRITE);//from ww w. jav a 2 s . com InputStream messageFileInputStream1 = null; InputStream messageFileInputStream2 = null; try { ClassPathResource fileResource = new ClassPathResource("imap/test-8bit-message.eml"); messageFileInputStream1 = new FileInputStream(fileResource.getFile()); Message message = new MimeMessage(Session.getDefaultInstance(new Properties()), messageFileInputStream1); String subject = message.getSubject(); // get original bytes for further comparation messageFileInputStream2 = new FileInputStream(fileResource.getFile()); byte[] original = ASCIIUtility.getBytes(messageFileInputStream2); Message[] messages = { message }; lfolder.appendMessages(messages); // The search is not implemented. // SearchTerm term = new HeaderTerm("X-Alfresco-Unique", "test8bit"); // messages = folder.search(term); // So wee need to get our test message's UID from the repo String messageXPath = companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME + "/*[like(@cm:title, $cm:title, true)]"; QueryParameterDefinition[] params = new QueryParameterDefinition[1]; params[0] = new QueryParameterDefImpl(ContentModel.PROP_TITLE, serviceRegistry.getDictionaryService().getDataType(DataTypeDefinition.TEXT), true, subject); List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, messageXPath, params, namespaceService, true); // does the message exist assertEquals(1, nodeRefs.size()); NodeRef messageNodeRef = nodeRefs.get(0); // get message UID Long dbid = (Long) nodeService.getProperty(messageNodeRef, ContentModel.PROP_NODE_DBID); // fetch the massage RFC822DATA data = getRFC822Message(lfolder, dbid); assertNotNull("Can't fetch a message from the repositiry", data); byte[] processed = ASCIIUtility.getBytes(data.getByteArrayInputStream()); assertTrue("Original message doesn't coincide to the message processed by the repository", Arrays.equals(original, processed)); } finally { if (messageFileInputStream1 != null) messageFileInputStream1.close(); if (messageFileInputStream2 != null) messageFileInputStream2.close(); } // close connection lfolder.close(true); lstore.close(); }
From source file:sendhtml.java
public sendhtml(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null;/* w w w. j a v a 2s .c o m*/ String mailer = "sendhtml"; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]"); System.exit(1); } else { break; } } try { if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } Properties props = System.getProperties(); // XXX - could use Session.getTransport() and Transport.connect() // XXX - assume we're using SMTP if (mailhost != null) props.put("mail.smtp.host", mailhost); // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); // construct the message Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); collect(in, msg); msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off Transport.send(msg); System.out.println("\nMail was sent successfully."); // Keep a copy, if requested. if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.liferay.mail.imap.IMAPAccessor.java
protected Folder getFolder(long folderId) throws MessagingException, PortalException { Store store = _imapConnection.getStore(true); com.liferay.mail.model.Folder folder = FolderLocalServiceUtil.getFolder(folderId); return store.getFolder(folder.getFullName()); }
From source file:sendhtml.java
public sendhtml(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null;/*from w ww . j a v a 2 s . c om*/ String mailer = "sendhtml"; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]"); System.exit(1); } else { break; } } try { if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } Properties props = System.getProperties(); // XXX - could use Session.getTransport() and Transport.connect() // XXX - assume we're using SMTP if (mailhost != null) props.put("mail.smtp.host", mailhost); // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); // construct the message Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); collect(in, msg); msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off Transport.send(msg); System.out.println("\nMail was sent successfully."); // Keep a copy, if requested. if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@SuppressWarnings("resource") @Test//from w w w . jav a2 s . c om public void testNoInitialIdleDelayWhenRecentNotSupported() throws Exception { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); ImapMailReceiver receiver = new ImapMailReceiver("imap:foo"); receiver = spy(receiver); receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet(); final IMAPFolder folder = mock(IMAPFolder.class); given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER)); given(folder.isOpen()).willReturn(false).willReturn(true); given(folder.exists()).willReturn(true); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); adapterAccessor.setPropertyValue("mailReceiver", receiver); Field storeField = AbstractMailReceiver.class.getDeclaredField("store"); storeField.setAccessible(true); Store store = mock(Store.class); given(store.isConnected()).willReturn(true); given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder); storeField.set(receiver, store); willAnswer(invocation -> folder).given(receiver).getFolder(); MimeMessage mailMessage = mock(MimeMessage.class); Flags flags = mock(Flags.class); given(mailMessage.getFlags()).willReturn(flags); final Message[] messages = new Message[] { mailMessage }; final AtomicInteger shouldFindMessagesCounter = new AtomicInteger(2); willAnswer(invocation -> { /* * Return the message from first invocation of waitForMessages() * and in receive(); then return false in the next call to * waitForMessages() so we enter idle(); counter will be reset * to 1 in the mocked idle(). */ if (shouldFindMessagesCounter.decrementAndGet() >= 0) { return messages; } else { return new Message[0]; } }).given(receiver).searchForNewMessages(); willAnswer(invocation -> null).given(receiver).fetchMessages(messages); willAnswer(invocation -> { Thread.sleep(5000); shouldFindMessagesCounter.set(1); return null; }).given(folder).idle(); adapter.start(); /* * Idle takes 5 seconds; if all is well, we should receive the first message * before then. */ assertNotNull(channel.receive(3000)); // We should not receive any more until the next idle elapses assertNull(channel.receive(3000)); assertNotNull(channel.receive(6000)); adapter.stop(); context.close(); }
From source file:com.treesbearfruit.icloudnotes.NotesSaver.java
public NotesSaver(String username, String password, String j, String wheretosave) throws Exception { // Get system properties Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props); // Get the store Store store = session.getStore("imaps"); String noteFolderLabel = ""; if (j.toLowerCase().equals("apple")) { noteFolderLabel = "Notes"; store.connect("imap.mail.me.com", username, password); // username without @icloud.com } else if (j.toLowerCase().equals("google")) { noteFolderLabel = "Notes"; store.connect("imap.gmail.com", username, password); } else {/*w ww .j a v a2s .c o m*/ throw new Exception("Notesprovider not implemented!"); } String timestamp = new java.text.SimpleDateFormat("dd_MM_yyyy_hh_mm_ss").format(new Date()); String backup_directory = wheretosave + (wheretosave.endsWith(File.separator) ? "" : File.separator) + noteFolderLabel + "_" + timestamp + File.separator; // saves main folder save(store, backup_directory, noteFolderLabel); // folder..s Folder mainnotefolder = store.getFolder(noteFolderLabel); System.out.println("found " + mainnotefolder.list().length + " note folders"); Folder[] f = mainnotefolder.list(); for (Folder fd : f) { String backup_directory_i = backup_directory + fd.getName(); save(store, backup_directory_i, noteFolderLabel + "/" + fd.getName()); } // Close connection store.close(); }
From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java
/** * {@inheritDoc}//w w w .ja va 2 s . com * * @see ch.entwine.weblounge.common.scheduler.JobWorker#execute(java.lang.String, * java.util.Dictionary) */ public void execute(String name, Dictionary<String, Serializable> ctx) throws JobException { Site site = (Site) ctx.get(Site.class.getName()); // Make sure the site is ready to accept content if (site.getContentRepository().isReadOnly()) { logger.warn("Unable to publish e-mail messages to site '{}': repository is read only", site); return; } WritableContentRepository repository = (WritableContentRepository) site.getContentRepository(); // Extract the configuration from the job properties String provider = (String) ctx.get(OPT_PROVIDER); Account account = null; try { if (StringUtils.isBlank(provider)) { provider = DEFAULT_PROVIDER; } account = new Account(ctx); } catch (IllegalArgumentException e) { throw new JobException(this, e); } // Connect to the server Properties sessionProperties = new Properties(); Session session = Session.getDefaultInstance(sessionProperties, null); Store store = null; Folder inbox = null; try { // Connect to the server try { store = session.getStore(provider); store.connect(account.getHost(), account.getLogin(), account.getPassword()); } catch (NoSuchProviderException e) { throw new JobException(this, "Unable to connect using unknown e-mail provider '" + provider + "'", e); } catch (MessagingException e) { throw new JobException(this, "Error connecting to " + provider + " account " + account, e); } // Open the account's inbox try { inbox = store.getFolder(INBOX); if (inbox == null) throw new JobException(this, "No inbox found at " + account); inbox.open(Folder.READ_WRITE); } catch (MessagingException e) { throw new JobException(this, "Error connecting to inbox at " + account, e); } // Get the messages from the server try { for (Message message : inbox.getMessages()) { if (!message.isSet(Flag.SEEN)) { try { Page page = aggregate(message, site); message.setFlag(Flag.DELETED, true); repository.put(page, true); logger.info("E-Mail message published at {}", page.getURI()); } catch (Exception e) { logger.info("E-Mail message discarded: {}", e.getMessage()); message.setFlag(Flag.SEEN, true); // TODO: Reply to sender if the "from" field exists } } } } catch (MessagingException e) { throw new JobException(this, "Error loading e-mail messages from inbox", e); } // Close the connection // but don't remove the messages from the server } finally { if (inbox != null) { try { inbox.close(true); } catch (MessagingException e) { throw new JobException(this, "Error closing inbox", e); } } if (store != null) { try { store.close(); } catch (MessagingException e) { throw new JobException(this, "Error closing connection to e-mail server", e); } } } }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@Test // see INT-1801 public void testImapLifecycleForRaceCondition() throws Exception { for (int i = 0; i < 1000; i++) { final ImapMailReceiver receiver = new ImapMailReceiver("imap://foo"); Store store = mock(Store.class); Folder folder = mock(Folder.class); given(folder.exists()).willReturn(true); given(folder.isOpen()).willReturn(true); given(folder.search((SearchTerm) Mockito.any())).willReturn(new Message[] {}); given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder); given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER)); DirectFieldAccessor df = new DirectFieldAccessor(receiver); df.setPropertyValue("store", store); receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet();// ww w .j av a 2 s . co m new Thread(() -> { try { receiver.receive(); } catch (javax.mail.MessagingException e) { if (e.getCause() instanceof NullPointerException) { failed.getAndIncrement(); } } }).start(); new Thread(() -> { try { receiver.destroy(); } catch (Exception ignore) { // ignore } }).start(); } assertEquals(0, failed.get()); }