List of usage examples for javax.mail Store isConnected
public synchronized boolean isConnected()
From source file:com.aurel.track.util.emailHandling.SyncStore.java
public synchronized static boolean connect(Store _store, String _protocol, String _host, int _port, String _user, String _password) { ConnectionPoint cp = getConnPoint(_store, _protocol, _host, _port, _user, _password); boolean connected = false; try {// w w w.java 2 s . com Store store = cp.getStore(); if (!store.isConnected()) { cp.getStore().connect(_host, _port, _user, _password); } ++cp.connectionCount; LOGGER.debug("Connecting store: connectionCount = " + cp.connectionCount); connected = true; } catch (Exception e) { connected = false; if (LogThrottle.isReady("Syncstore1", 240)) { LOGGER.warn("Could not connect..." + e.getMessage()); } LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return connected; }
From source file:com.cws.esolutions.core.utils.EmailUtils.java
/** * Processes and sends an email message as generated by the requesting * application. This method is utilized with a JNDI datasource. * * @param dataSource - The email message * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise * @param authList - If authRequired is true, this must be populated with the auth info * @return List - The list of email messages in the mailstore * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing *//* w w w. j a v a2 s . co m*/ public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException { final String methodName = EmailUtils.CNAME + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("dataSource: {}", dataSource); DEBUGGER.debug("authRequired: {}", authRequired); DEBUGGER.debug("authList: {}", authList); } Folder mailFolder = null; Session mailSession = null; Folder archiveFolder = null; List<EmailMessage> emailMessages = null; Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, -24); final Long TIME_PERIOD = cal.getTimeInMillis(); final URLName URL_NAME = (authRequired) ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1)) : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, null, null); if (DEBUG) { DEBUGGER.debug("timePeriod: {}", TIME_PERIOD); DEBUGGER.debug("URL_NAME: {}", URL_NAME); } try { // Set up mail session mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator()) : Session.getDefaultInstance(dataSource); if (DEBUG) { DEBUGGER.debug("mailSession: {}", mailSession); } if (mailSession == null) { throw new MessagingException("Unable to configure email services"); } mailSession.setDebug(DEBUG); Store mailStore = mailSession.getStore(URL_NAME); mailStore.connect(); if (DEBUG) { DEBUGGER.debug("mailStore: {}", mailStore); } if (!(mailStore.isConnected())) { throw new MessagingException("Failed to connect to mail service. Cannot continue."); } mailFolder = mailStore.getFolder("inbox"); archiveFolder = mailStore.getFolder("archive"); if (!(mailFolder.exists())) { throw new MessagingException("Requested folder does not exist. Cannot continue."); } mailFolder.open(Folder.READ_WRITE); if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) { throw new MessagingException("Failed to open requested folder. Cannot continue"); } if (!(archiveFolder.exists())) { archiveFolder.create(Folder.HOLDS_MESSAGES); } Message[] mailMessages = mailFolder.getMessages(); if (mailMessages.length == 0) { throw new MessagingException("No messages were found in the provided store."); } emailMessages = new ArrayList<EmailMessage>(); for (Message message : mailMessages) { if (DEBUG) { DEBUGGER.debug("MailMessage: {}", message); } // validate the message here String messageId = message.getHeader("Message-ID")[0]; Long messageDate = message.getReceivedDate().getTime(); if (DEBUG) { DEBUGGER.debug("messageId: {}", messageId); DEBUGGER.debug("messageDate: {}", messageDate); } // only get emails for the last 24 hours // this should prevent us from pulling too // many emails if (messageDate >= TIME_PERIOD) { // process it Multipart attachment = (Multipart) message.getContent(); Map<String, InputStream> attachmentList = new HashMap<String, InputStream>(); for (int x = 0; x < attachment.getCount(); x++) { BodyPart bodyPart = attachment.getBodyPart(x); if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) { continue; } attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream()); } List<String> toList = new ArrayList<String>(); List<String> ccList = new ArrayList<String>(); List<String> bccList = new ArrayList<String>(); List<String> fromList = new ArrayList<String>(); for (Address from : message.getFrom()) { fromList.add(from.toString()); } if ((message.getRecipients(RecipientType.TO) != null) && (message.getRecipients(RecipientType.TO).length != 0)) { for (Address to : message.getRecipients(RecipientType.TO)) { toList.add(to.toString()); } } if ((message.getRecipients(RecipientType.CC) != null) && (message.getRecipients(RecipientType.CC).length != 0)) { for (Address cc : message.getRecipients(RecipientType.CC)) { ccList.add(cc.toString()); } } if ((message.getRecipients(RecipientType.BCC) != null) && (message.getRecipients(RecipientType.BCC).length != 0)) { for (Address bcc : message.getRecipients(RecipientType.BCC)) { bccList.add(bcc.toString()); } } EmailMessage emailMessage = new EmailMessage(); emailMessage.setMessageTo(toList); emailMessage.setMessageCC(ccList); emailMessage.setMessageBCC(bccList); emailMessage.setEmailAddr(fromList); emailMessage.setMessageAttachments(attachmentList); emailMessage.setMessageDate(message.getSentDate()); emailMessage.setMessageSubject(message.getSubject()); emailMessage.setMessageBody(message.getContent().toString()); emailMessage.setMessageSources(message.getHeader("Received")); if (DEBUG) { DEBUGGER.debug("emailMessage: {}", emailMessage); } emailMessages.add(emailMessage); if (DEBUG) { DEBUGGER.debug("emailMessages: {}", emailMessages); } } // archive it archiveFolder.open(Folder.READ_WRITE); if (archiveFolder.isOpen()) { mailFolder.copyMessages(new Message[] { message }, archiveFolder); message.setFlag(Flags.Flag.DELETED, true); } } } catch (IOException iox) { throw new MessagingException(iox.getMessage(), iox); } catch (MessagingException mex) { throw new MessagingException(mex.getMessage(), mex); } finally { try { if ((mailFolder != null) && (mailFolder.isOpen())) { mailFolder.close(true); } if ((archiveFolder != null) && (archiveFolder.isOpen())) { archiveFolder.close(false); } } catch (MessagingException mx) { ERROR_RECORDER.error(mx.getMessage(), mx); } } return emailMessages; }
From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java
protected void checkStoreForTestConnection(final Store store) { if (!store.isConnected()) { IMAPUtils.close(store);// ww w. j av a 2s . com throw new RuntimeException("Store not connected"); } if (!store.getURLName().getUsername().toLowerCase().startsWith("es_imapriver_unittest")) { IMAPUtils.close(store); throw new RuntimeException( "User " + store.getURLName().getUsername() + " belongs not to a valid test mail connection"); } }
From source file:com.liferay.mail.imap.IMAPConnection.java
public Store getStore(boolean useOldStores) throws MailException { Store store = null; try {/*from ww w . j a v a2s . c om*/ String storeKey = _incomingHostName.concat(_outgoingHostName).concat(_login); if (useOldStores) { store = _allStores.get(storeKey); if ((store != null) && !store.isConnected()) { store.close(); store = null; } } if (store == null) { Session session = getSession(); if (_incomingSecure) { store = session.getStore("imaps"); } else { store = session.getStore("imap"); } store.connect(_incomingHostName, _incomingPort, _login, _password); if (useOldStores) { _allStores.put(storeKey, store); } } return store; } catch (MessagingException me) { throw new MailException(MailException.ACCOUNT_INCOMING_CONNECTION_FAILED, me); } }
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();//from www . j ava 2 s . c o 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 . j a v a 2s . 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.springframework.integration.mail.ImapMailReceiverTests.java
@SuppressWarnings("resource") @Test//from w w w. j a v a 2 s .c o m 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.cisco.iwe.services.util.EmailMonitor.java
/** * This method returns the corresponding JSON response.'Success = true' in case the Mail contents get stored in the database successfully. 'Success = false' in case of any errors **//*from w w w .j a va 2 s . c o m*/ public String monitorEmailAndLoadDB() { License license = new License(); license.setLicense(EmailParseConstants.ocrLicenseFile); Store emailStore = null; Folder folder = null; Properties props = new Properties(); logger.info("EmailMonitor monitorEmailAndLoadDB Enter (+)"); // Setting session and Store information // MailServerConnectivity - get the email credentials based on the environment String[] mailCredens = getEmailCredens(); final String username = mailCredens[0]; final String password = mailCredens[1]; logger.info("monitorEmailAndLoadDB : Email ID : " + username); try { logger.info("EmailMonitor.monitorEmailAndLoadDB get the mail server properties"); props.put(EmailParseConstants.emailAuthKey, "true"); props.put(EmailParseConstants.emailHostKey, prop.getProperty(EmailParseConstants.emailHost)); props.put(EmailParseConstants.emailPortKey, prop.getProperty(EmailParseConstants.emailPort)); props.put(EmailParseConstants.emailTlsKey, "true"); logger.info("EmailMonitor.monitorEmailAndLoadDB create the session object with mail server properties"); Session session = Session.getDefaultInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); // Prod-MailServerConnectivity - create the POP3 store object and // connect with the pop server logger.info("monitorEmailAndLoadDB : create the POP3 store object"); emailStore = (Store) session.getStore(prop.getProperty(EmailParseConstants.emailType)); logger.info("monitorEmailAndLoadDB : Connecting to Store :" + emailStore.toString()); emailStore.connect(prop.getProperty(EmailParseConstants.emailHost), Integer.parseInt(prop.getProperty(EmailParseConstants.emailPort)), username, password); logger.info("monitorEmailAndLoadDB : Connection Status:" + emailStore.isConnected()); // create the folder object folder = emailStore.getFolder(prop.getProperty(EmailParseConstants.emailFolder)); // Check if Inbox exists if (!folder.exists()) { logger.error("monitorEmailAndLoadDB : No INBOX exists..."); System.exit(0); } // Open inbox and read messages logger.info("monitorEmailAndLoadDB : Connected to Folder"); folder.open(Folder.READ_WRITE); // retrieve the messages from the folder in an array and process it Message[] msgArr = folder.getMessages(); // Read each message and delete the same once data is stored in DB logger.info("monitorEmailAndLoadDB : Message length::::" + msgArr.length); SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat); Date sent = null; String emailContent = null; String contentType = null; // for (int i = 0; i < msg.length; i++) { for (int i = msgArr.length - 1; i > msgArr.length - 2; i--) { Message message = msgArr[i]; if (!message.isSet(Flags.Flag.SEEN)) { try { sent = msgArr[i].getSentDate(); contentType = message.getContentType(); String fileType = null; byte[] byteArr = null; String validAttachments = EmailParseConstants.validAttachmentTypes; if (contentType.contains("multipart")) { Multipart multiPart = (Multipart) message.getContent(); int numberOfParts = multiPart.getCount(); for (int partCount = 0; partCount < numberOfParts; partCount++) { MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount); InputStream inStream = (InputStream) part.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = inStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); byteArr = buffer.toByteArray(); if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { fileType = part.getFileName().substring(part.getFileName().lastIndexOf("."), part.getFileName().length()); String fileDir = part.getFileName(); if (validAttachments.contains(fileType)) { part.saveFile(fileDir); saveAttachmentAndText(message.getFrom()[0].toString(), message.getSubject(), byteArr, emailContent.getBytes(), fileType, sent, fileType.equalsIgnoreCase(".PDF") ? scanPDF(fileDir) : scanImage(fileDir).toString()); deleteFile(fileDir); } else { sendNotification(); } } else { // this part may be the message content emailContent = part.getContent().toString(); } } } else if (contentType.contains("text/plain") || contentType.contains("text/html")) { Object content = message.getContent(); if (content != null) { emailContent = content.toString(); } } message.setFlag(Flags.Flag.DELETED, false); logger.info( "monitorEmailAndLoadDB : loadSuccess : Mail Parsed for : " + message.getSubject()); logger.info("monitorEmailAndLoadDB : loadSuccess : Created at : " + sdf2.format(sent)); logger.info("Message deleted"); } catch (IOException e) { logger.error("IO Exception in email monitoring: " + e); logger.error( "IO Exception in email monitoring message: " + Arrays.toString(e.getStackTrace())); } catch (SQLException sexp) { logger.error("SQLException Occurred GetSpogDetails-db2 :", sexp); buildErrorJson(ExceptionConstants.sqlErrCode, ExceptionConstants.sqlErrMsg); } catch (Exception e) { logger.error("Unknown Exception in email monitoring: " + e); logger.error("Unknown Exception in email monitoring message: " + Arrays.toString(e.getStackTrace())); } } } // Close folder and store folder.close(true); emailStore.close(); } catch (NoSuchProviderException e) { logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring: " + e); logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring message: " + Arrays.toString(e.getStackTrace())); } catch (MessagingException e) { logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e); logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring message: " + Arrays.toString(e.getStackTrace())); } finally { if (folder != null && folder.isOpen()) { // Close folder and store try { folder.close(true); emailStore.close(); } catch (MessagingException e) { logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e); logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + Arrays.toString(e.getStackTrace())); } } } logger.info("EmailMonitor monitorEmailAndLoadDB Exit (-)"); return buildSuccessJson().toString(); }
From source file:net.wastl.webmail.server.WebMailSession.java
protected Store connectStore(String host, String protocol, String login, String password) throws MessagingException { /* Check whether the domain of this user allows to connect to the host */ WebMailVirtualDomain vdom = parent.getStorage().getVirtualDomain(user.getDomain()); if (!vdom.isAllowedHost(host)) { throw new MessagingException("You are not allowed to connect to this host"); }// w w w.j a v a2 s . co m imapBasedir = vdom.getImapBasedir(); /* Check if this host is already connected. Use connection if true, create a new one if false. */ Store st = stores.get(host + "-" + protocol); if (st == null) { st = mailsession.getStore(protocol); stores.put(host + "-" + protocol, st); } /* Maybe this is a new store or this store has been disconnected. Reconnect if this is the case. */ if (!st.isConnected()) { try { st.connect(host, login, password); log.info("Mail: Connection to " + st.toString() + "."); } catch (AuthenticationFailedException ex) { /* If login fails, try the login_password */ if (!login_password.equals(password) && parent.getStorage().getConfig("FOLDER TRY LOGIN PASSWORD").toUpperCase().equals("YES")) { st.connect(host, login, login_password); log.info("Mail: Connection to " + st.toString() + ", second attempt with login password succeeded."); } else { throw ex; } } } return st; }