List of usage examples for javax.mail Folder READ_WRITE
int READ_WRITE
To view the source code for javax.mail Folder READ_WRITE.
Click Source Link
From source file:org.eurekastreams.server.service.email.ImapEmailIngester.java
/** * Ingests email from a mailbox.//from w ww. ja v a 2 s .c o m */ public void execute() { // get message store Store store; try { long startTime = System.nanoTime(); store = storeFactory.getStore(); log.debug("Connected to mail store in {}ns", System.nanoTime() - startTime); } catch (MessagingException ex) { log.error("Error getting message store.", ex); return; } try { // get folders Folder inputFolder = store.getFolder(inputFolderName); if (!inputFolder.exists()) { log.error("Input folder {} does not exist.", inputFolderName); return; } Folder successFolder = null; if (StringUtils.isNotBlank(successFolderName)) { successFolder = store.getFolder(successFolderName); if (!successFolder.exists()) { log.error("Success folder {} does not exist.", successFolderName); return; } } Folder discardFolder = null; if (StringUtils.isNotBlank(discardFolderName)) { discardFolder = store.getFolder(discardFolderName); if (!discardFolder.exists()) { log.error("Discard folder {} does not exist.", discardFolderName); return; } } Folder errorFolder = null; if (StringUtils.isNotBlank(errorFolderName)) { errorFolder = store.getFolder(errorFolderName); if (!errorFolder.exists()) { log.error("Error folder {} does not exist.", errorFolderName); return; } } inputFolder.open(Folder.READ_WRITE); // fetch messages // Note: Not preloading CONTENT_INFO. For some reason, preloading the content info (IMAP BODYSTRUCTURE) // causes the call to getContent to return empty. (As if there was a bug where getContent saw the cached // body structure and thought that the content itself was cached, but I'd think a bug like that would have // been found by many people and fixed long ago, so I'm assuming it's something else.) FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); Message[] msgs = inputFolder.getMessages(); inputFolder.fetch(msgs, fp); log.debug("About to process {} messages", msgs.length); // process each message if (msgs.length > 0) { List<Message> successMessages = new ArrayList<Message>(); List<Message> errorMessages = new ArrayList<Message>(); List<Message> discardMessages = new ArrayList<Message>(); List<Message> responseMessages = new ArrayList<Message>(); for (int i = 0; i < msgs.length; i++) { Message message = msgs[i]; try { boolean processed = messageProcessor.execute(message, responseMessages); (processed ? successMessages : discardMessages).add(message); } catch (Exception ex) { log.error("Failed to process email message.", ex); errorMessages.add(message); } } // send response messages for (Message responseMessage : responseMessages) { emailerFactory.sendMail(responseMessage); } // move and purge messages if (successFolder != null && !successMessages.isEmpty()) { inputFolder.copyMessages(successMessages.toArray(new Message[successMessages.size()]), successFolder); } if (discardFolder != null && !discardMessages.isEmpty()) { inputFolder.copyMessages(discardMessages.toArray(new Message[discardMessages.size()]), discardFolder); } if (errorFolder != null && !errorMessages.isEmpty()) { inputFolder.copyMessages(errorMessages.toArray(new Message[errorMessages.size()]), errorFolder); } for (int i = 0; i < msgs.length; i++) { msgs[i].setFlag(Flag.DELETED, true); } log.info("{} messages processed: {} successful, {} discarded, {} failed.", new Object[] { msgs.length, successMessages.size(), discardMessages.size(), errorMessages.size() }); } // close folder inputFolder.close(true); } catch (MessagingException ex) { log.error("Error ingesting email.", ex); } catch (Exception ex) { log.error("Error ingesting email.", ex); } finally { // close store try { store.close(); } catch (MessagingException ex) { log.error("Error closing message store.", ex); } } }
From source file:gmailclientfx.controllers.ObrisaneController.java
public void fetchObrisane() { ObservableList<MyMessage> data = FXCollections.observableArrayList(); stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId")); stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject")); stupacFrom.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender")); stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived")); obrisaneTable.setItems(data);//w w w . ja va 2 s. c o m obrisaneTable.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.isPrimaryButtonDown() && event.getClickCount() == 2) { MyMessage selectedMsg = obrisaneTable.getSelectionModel().getSelectedItem(); PregledEmailaHelper.setMsg(selectedMsg); try { Parent root; FXMLLoader loader = new FXMLLoader(); loader.setLocation( getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml")); root = loader.load(); Stage stage = new Stage(); stage.setScene(new Scene(root)); stage.show(); PregledEmailaController pgec = loader.getController(); stage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { pgec.bodyWebViewEngine.load(null); System.out.println("Closing form!"); } }); stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - " + PregledEmailaHelper.getMsg().getSender()); } catch (IOException ex) { Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex); } } } }); try { IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(), GmailClient.getAccesToken(), true); Folder obrisane = null; Folder[] folders = store.getDefaultFolder().list("*"); for (Folder f : folders) { IMAPFolder imapFolder = (IMAPFolder) f; for (String att : imapFolder.getAttributes()) { if ("\\Trash".equals(att)) { obrisane = f; } } } obrisane.open(Folder.READ_WRITE); MimeMessage[] seenMessages = (MimeMessage[]) obrisane .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true)); for (int i = 0; i < seenMessages.length; i++) { MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "DELETED"); data.add(msg); } MimeMessage[] unseenMessages = (MimeMessage[]) obrisane .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); for (int i = 0; i < unseenMessages.length; i++) { MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "DELETED"); data.add(msg); } obrisane.close(false); store.close(); } catch (Exception ex) { Logger.getLogger(ObrisaneController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:gmailclientfx.controllers.InboxController.java
public void fetchInbox() { ObservableList<MyMessage> data = FXCollections.observableArrayList(); stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId")); stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject")); stupacPosiljatelj.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender")); stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived")); Platform.runLater(() -> {//ww w . j a v a2 s .c o m inboxTable.setItems(data); }); inboxTable.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.isPrimaryButtonDown() && event.getClickCount() == 2) { MyMessage selectedMsg = inboxTable.getSelectionModel().getSelectedItem(); PregledEmailaHelper.setMsg(selectedMsg); try { Parent root; FXMLLoader loader = new FXMLLoader(); loader.setLocation( getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml")); root = loader.load(); Stage stage = new Stage(); stage.setScene(new Scene(root)); stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - " + PregledEmailaHelper.getMsg().getSender()); stage.show(); PregledEmailaController pgec = loader.getController(); stage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { pgec.bodyWebViewEngine.load(null); System.out.println("Closing form!"); } }); } catch (IOException ex) { Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex); } } } }); try { IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(), GmailClient.getAccesToken(), true); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); int getSeenCount = inbox.getMessageCount(); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfileItem.FLAGS); fp.add(FetchProfileItem.CONTENT_INFO); fp.add("X-mailer"); MimeMessage[] seenMessages = (MimeMessage[]) inbox .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true)); for (int i = 0; i < seenMessages.length; i++) { MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "INBOX"); data.add(msg); } MimeMessage[] unseenMessages = (MimeMessage[]) inbox .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); for (int i = 0; i < unseenMessages.length; i++) { MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "INBOX"); data.add(msg); } inbox.close(false); store.close(); } catch (Exception ex) { Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:gmailclientfx.controllers.NedovrseneController.java
public void fetchNedovrsene() { ObservableList<MyMessage> data = FXCollections.observableArrayList(); stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId")); stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject")); stupacTo.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender")); stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived")); nedovrseneTable.setItems(data);//from w w w. jav a 2 s .c o m nedovrseneTable.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.isPrimaryButtonDown() && event.getClickCount() == 2) { MyMessage selectedMsg = nedovrseneTable.getSelectionModel().getSelectedItem(); PregledEmailaHelper.setMsg(selectedMsg); try { Parent root; FXMLLoader loader = new FXMLLoader(); loader.setLocation( getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml")); root = loader.load(); Stage stage = new Stage(); stage.setScene(new Scene(root)); stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - " + PregledEmailaHelper.getMsg().getSender()); stage.show(); PregledEmailaController pgec = loader.getController(); stage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { pgec.bodyWebViewEngine.load(null); System.out.println("Closing form!"); } }); } catch (IOException ex) { Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex); } } } }); try { IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(), GmailClient.getAccesToken(), true); Folder nedovrsene = null; Folder[] folders = store.getDefaultFolder().list("*"); for (Folder f : folders) { IMAPFolder imapFolder = (IMAPFolder) f; for (String att : imapFolder.getAttributes()) { if ("\\Drafts".equals(att)) { nedovrsene = f; } } } nedovrsene.open(Folder.READ_WRITE); MimeMessage[] seenMessages = (MimeMessage[]) nedovrsene .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true)); for (int i = 0; i < seenMessages.length; i++) { MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "DRAFT"); data.add(msg); } MimeMessage[] unseenMessages = (MimeMessage[]) nedovrsene .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); for (int i = 0; i < unseenMessages.length; i++) { MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "DRAFT"); data.add(msg); } nedovrsene.close(false); store.close(); } catch (Exception ex) { Logger.getLogger(NedovrseneController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:ru.retbansk.utils.scheduled.impl.ReadEmailAndConvertToXmlSpringImpl.java
/** * Loads email properties, reads email messages, * converts their multipart bodies into string, * send error emails if message doesn't contain valid report and at last returns a reversed Set of the Valid Reports * <p><b> deletes messages//w ww .j a v a2 s. com * @see #readEmail() * @see #convertToXml(HashSet) * @see ru.retbansk.utils.scheduled.ReplyManager * @return HashSet<DayReport> of the Valid Day Reports */ @Override public HashSet<DayReport> readEmail() throws Exception { Properties prop = loadProperties(); String host = prop.getProperty("host"); String user = prop.getProperty("user"); String password = prop.getProperty("password"); path = prop.getProperty("path"); // Get system properties Properties properties = System.getProperties(); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Get a Store object that implements the specified protocol. Store store = session.getStore("pop3"); // Connect to the current host using the specified username and // password. store.connect(host, user, password); // Create a Folder object corresponding to the given name. Folder folder = store.getFolder("inbox"); // Open the Folder. folder.open(Folder.READ_WRITE); HashSet<DayReport> dayReportSet = new HashSet<DayReport>(); try { // Getting messages from the folder Message[] message = folder.getMessages(); // Reversing the order in the array with the use of Set to make the last one final Collections.reverse(Arrays.asList(message)); // Reading messages. String body; for (int i = 0; i < message.length; i++) { DayReport dayReport = null; dayReport = new DayReport(); dayReport.setPersonId(((InternetAddress) message[i].getFrom()[0]).getAddress()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+3")); calendar.setTime(message[i].getSentDate()); dayReport.setCalendar(calendar); dayReport.setSubject(message[i].getSubject()); List<TaskReport> reportList = null; //Release the string from email message body body = ""; Object content = message[i].getContent(); if (content instanceof java.lang.String) { body = (String) content; } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; for (int j = 0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); if (disposition == null) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } } } //Put the string (body of email message) and get list of valid reports else send error reportList = new ArrayList<TaskReport>(); reportList = giveValidReports(body, message[i].getSentDate()); //Check for valid day report. To be valid it should have size of reportList > 0. if (reportList.size() > 0) { // adding valid ones to Set dayReport.setReportList(reportList); dayReportSet.add(dayReport); } else { // This message doesn't have valid reports. Sending an error reply. logger.info("Invalid Day Report detected. Sending an error reply"); ReplyManager man = new ReplyManagerSimpleImpl(); man.sendError(dayReport); } // Delete message message[i].setFlag(Flags.Flag.DELETED, true); } } finally { // true tells the mail server to expunge deleted messages. folder.close(true); store.close(); } return dayReportSet; }
From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java
/** * This method read verification e-mail from Gmail inbox and returns the verification URL. * * @return verification redirection URL. * @throws Exception//from w ww . ja v a2 s . c o m */ 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; }
From source file:org.webguitoolkit.messagebox.mail.MailChannel.java
/** * /*w w w . ja v a2 s . co m*/ */ @Override public List<IMessage> receive(boolean clear) { List<IMessage> result = new ArrayList<IMessage>(); try { String user = properties.getProperty("pop3.login.user"); String password = properties.getProperty("pop3.login.password"); String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties pop3Props = new Properties(); pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false"); pop3Props.setProperty("mail.pop3.port", properties.getProperty("pop3.port")); pop3Props.setProperty("mail.pop3.socketFactory.port", properties.getProperty("pop3.port")); URLName url = new URLName("pop3", properties.getProperty("pop3.host"), Integer.valueOf(properties.getProperty("pop3.port")), "", user, password); Session session = Session.getInstance(pop3Props, null); Store store = new POP3SSLStore(session, url); store.connect(); // Open the Folder Folder folder = store.getDefaultFolder(); folder = folder.getFolder("INBOX"); if (folder == null) { throw new RuntimeException("Invalid folder INBOX"); } // try to open read/write and if that fails try read-only try { folder.open(Folder.READ_WRITE); } catch (MessagingException ex) { folder.open(Folder.READ_ONLY); } int count = folder.getMessageCount(); // Message numbers start at 1 for (int i = 1; i <= count; i++) { // Get a message by its sequence number Message m = folder.getMessage(i); Address[] from = m.getFrom(); String type = from[0].getType(); IMessage message = new MailMessage(from[0].toString(), this, m.getSubject(), getContent(m)); result.add(message); // delete message ? if (clear) m.setFlag(Flags.Flag.DELETED, true); } // "true" actually deletes flagged messages from folder folder.close(clear); store.close(); } catch (Exception e) { throw new RuntimeException(e); } return result; }
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 **//* w w w. ja v a 2 s. co 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:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java
public void generateMailNotification(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName, String mailStorePassword, String notificationType, String fromFilter, String subjectFilter) throws Exception { Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName, mailStorePassword);// www . j a v a2 s . c om try { // connects to the message store Store store = session.getStore(mailStoreProtocol); store.connect(mailStoreHost, mailStoreUserName, mailStorePassword); logger.info("connected to message store"); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_WRITE); // check if fromFilter is specified List<String> fromFilterList = null; if (StringUtils.isNotBlank(fromFilter)) { String[] fromFilterArray = StringUtils.split(fromFilter, "|"); fromFilterList = Arrays.asList(fromFilterArray); } // check if subjectFilter is specified List<String> subjectFilterList = null; if (StringUtils.isNotBlank(subjectFilter)) { String[] subjectFilterArray = StringUtils.split(subjectFilter, "|"); subjectFilterList = Arrays.asList(subjectFilterArray); } Map<String, Object> context = new HashMap<String, Object>(); // fetches new messages from server Message[] messages = folderInbox.getMessages(); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; Address[] fromAddress = msg.getFrom(); String address = fromAddress[0].toString(); String from = extractFromAddress(address); if (StringUtils.isBlank(from)) { logger.warn("From Address is not proper " + from); return; } boolean isValidFrom = isValidMatch(fromFilterList, from); // filter based on fromFilter specified if (null == fromFilterList || isValidFrom) { String subject = msg.getSubject(); boolean isValidSubject = isValidMatch(subjectFilterList, subject); if (null == subjectFilterList || isValidSubject) { String toList = parseAddresses(msg.getRecipients(RecipientType.TO)); String ccList = parseAddresses(msg.getRecipients(RecipientType.CC)); String sentDate = msg.getSentDate().toString(); String messageContent = ""; try { Object content = msg.getContent(); if (content != null) { messageContent = content.toString(); } } catch (Exception ex) { messageContent = "[Error downloading content]"; ex.printStackTrace(); } context.put("from", from); context.put("to", toList); context.put("cc", ccList); context.put("subject", subject); context.put("messagebody", messageContent); context.put("sentdate", sentDate); notificationController.createNotification(notificationType, context); msg.setFlag(Flag.DELETED, true); } else { logger.warn("subjectFilter doesn't match"); } } else { logger.warn("this email originated from " + address + " , which does not match fromAddress specified in the rule, it should be " + fromFilter.toString()); } } // disconnect and delete messages marked as DELETED folderInbox.close(true); store.close(); } catch (NoSuchProviderException ex) { logger.warn("No provider for protocol: " + mailStoreProtocol + " " + ex); } catch (MessagingException ex) { logger.error("Could not connect to the message store" + ex); } }
From source file:org.openadaptor.auxil.connector.mail.MailConnection.java
/** * Opens the named folder in READ/WRITE mode * * @throws MessagingException if there is a comms error or if the folder could not * be found or we failed to create it/*from w w w . java 2 s.c om*/ */ public Folder openFolder(String fldr, boolean create) throws MessagingException { if (store == null || !store.isConnected()) connect(); Folder f = store.getFolder(fldr); log.debug("Folder [" + fldr + "] exists? " + f.exists()); // Note that a Folder object is returned even if the named folder does not // physically exist on the Store so we have to test for it explicitly. if (!f.exists()) { // we've not been asked to create the folder so this is an error if (!create) throw new MessagingException("Error opening folder [" + fldr + "]: Folder not found"); // try to create the folder if (!f.create(Folder.HOLDS_MESSAGES)) throw new MessagingException("Failed to create folder [" + fldr + "]"); log.info("Created folder [" + fldr + "]"); } f.open(Folder.READ_WRITE); log.debug("Folder [" + fldr + "] opened"); return f; }