List of usage examples for javax.mail Folder exists
public abstract boolean exists() throws MessagingException;
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 **/// ww w . j av a 2 s.c om 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:com.sonicle.webtop.mail.Service.java
public String getSentFolder(Identity ident) { UserProfile profile = environment.getProfile(); String sentfolder = mainAccount.getFolderSent(); if (ident != null) { MailAccount account = getAccount(ident); String mainfolder = ident.getMainFolder(); if (mainfolder != null && mainfolder.trim().length() > 0) { String newsentfolder = mainfolder + account.getFolderSeparator() + account.getLastFolderName(sentfolder); try { Folder folder = account.getFolder(newsentfolder); if (folder.exists()) { sentfolder = newsentfolder; }//from w w w .j a va2s.com } catch (MessagingException exc) { logger.error("Error on identity {}/{} Sent Folder", profile.getUserId(), ident.getEmail(), exc); } } } return sentfolder; }
From source file:com.sonicle.webtop.mail.Service.java
private FolderCache determineSentFolder(MailAccount account, SimpleMessage msg) throws MessagingException { String draftsfolder = account.getFolderDrafts(); Identity ident = msg.getFrom(); if (ident != null) { String mainfolder = ident.getMainFolder(); if (mainfolder != null && mainfolder.trim().length() > 0) { String newdraftsfolder = mainfolder + account.getFolderSeparator() + account.getLastFolderName(draftsfolder); try { Folder folder = account.getFolder(newdraftsfolder); if (folder.exists()) { draftsfolder = newdraftsfolder; }//from www. ja v a2 s . c o m } catch (MessagingException exc) { logger.error("Error on identity {}/{} Drafts Folder", environment.getProfile().getUserId(), ident.getEmail(), exc); } } } FolderCache fc = account.getFolderCache(draftsfolder); return fc; }
From source file:com.sonicle.webtop.mail.Service.java
public void processGetFavoritesTree(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { //first call runs external checks if (!getFavoritesTreeDone) { for (MailAccount extacc : externalAccounts) { extacc.getFoldersThread().start(); }/* ww w . ja va 2 s . c om*/ getFavoritesTreeDone = true; } try { //synchronized(mft) { ArrayList<JsFolder> jsFolders = new ArrayList<>(); //out.print("{ data:["); MailUserSettings.FavoriteFolders favorites; boolean removeOldSetting = false; //use new setting if exists if (us.hasFavoriteFolders()) favorites = us.getFavoriteFolders(); //convert old setting else { MailUserSettings.Favorites off = us.getFavorites(); favorites = new MailUserSettings.FavoriteFolders(); for (String foldername : off) { favorites.add(new MailUserSettings.FavoriteFolder(MAIN_ACCOUNT_ID, foldername, foldername)); } removeOldSetting = true; } MailUserSettings.FavoriteFolders newFavorites = new MailUserSettings.FavoriteFolders(); ArrayList<FavoriteFolderData> ffds = new ArrayList<>(); for (int i = 0; i < favorites.size(); ++i) { MailUserSettings.FavoriteFolder ff = favorites.get(i); MailAccount account = getAccount(ff.accountId); if (account != null) { Folder folder = account.getFolder(ff.folderId); if (folder.exists()) { FolderCache fc = new FolderCache(account, folder, this, environment); newFavorites.add(ff); ffds.add(new FavoriteFolderData(fc, ff.description)); } } } us.setFavoriteFolders(newFavorites); //remove old setting if present if (removeOldSetting) { us.deleteOldFavoritesSetting(); } for (FavoriteFolderData ffd : ffds) { JsFolder jsFolder = createJsFolder(ffd.folderCache, true); jsFolder.folder = ffd.description; jsFolders.add(jsFolder); } //outputFolders(mainAccount, mainAccount.getDefaultFolder(), folders, false, true, jsFolders); new JsonResult("data", jsFolders).printTo(out, false); //out.println("], message: '' }"); //} } catch (Exception exc) { Service.logger.error("Exception", exc); new JsonResult(exc).printTo(out); } }