List of usage examples for javax.mail Store getFolder
public abstract Folder getFolder(URLName url) throws MessagingException;
From source file:org.zilverline.core.IMAPCollection.java
/** * Sets existsOnDisk based on whether the collection (contentDir) actually (now) sits on disk. * /*from ww w . j a v a 2s .c o m*/ * @todo the whole existsOnDisk construction is a little funny, refactor some time */ protected void setExistsOnDisk() { existsOnDisk = false; Store store = null; try { // try to connect to server and find folder log.debug("Connecting to IMAP server: " + host); Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props, null); store = session.getStore("imap"); log.debug("Connecting to " + host + " as " + user); store.connect(host, user, password); log.debug("Connected"); // start at the proper folder Folder topFolder = null; if (StringUtils.hasText(folder)) { topFolder = store.getFolder(folder); } else { topFolder = store.getDefaultFolder(); } existsOnDisk = (topFolder != null); } catch (NoSuchProviderException e) { log.warn("Can't connect to " + host, e); } catch (MessagingException e) { log.warn("Error while accessing IMAP server " + host, e); } finally { if (store != null) { try { store.close(); } catch (MessagingException e1) { log.error("Error closing IMAP server " + host, e1); } } } }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
private Folder testAttachmentsGuts(final ImapMailReceiver receiver) throws MessagingException, IOException { Store store = mock(Store.class); Folder folder = mock(Folder.class); given(folder.exists()).willReturn(true); given(folder.isOpen()).willReturn(true); Message message = new MimeMessage(null, new ClassPathResource("test.mail").getInputStream()); given(folder.search((SearchTerm) Mockito.any())).willReturn(new Message[] { 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();/*from ww w. ja va 2 s.c o m*/ return folder; }
From source file:be.ibridge.kettle.job.entry.getpop.JobEntryGetPOP.java
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = new Result(nr); result.setResult(false);//from w w w.j a v a2 s . c o m result.setNrErrors(1); FileObject fileObject = null; //Get system properties //Properties prop = System.getProperties(); Properties prop = new Properties(); //Create session object //Session sess = Session.getDefaultInstance(prop,null); Session sess = Session.getInstance(prop, null); sess.setDebug(true); try { int nbrmailtoretrieve = Const.toInt(firstmails, 0); fileObject = KettleVFS.getFileObject(getRealOutputDirectory()); // Check if output folder exists if (!fileObject.exists()) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.FolderNotExists1.Label") + getRealOutputDirectory() + Messages.getString("JobGetMailsFromPOP.FolderNotExists2.Label")); } else { String host = getRealServername(); String user = getRealUsername(); String pwd = getRealPassword(); Store st = null; if (!getUseSSL()) { //Create POP3 object st = sess.getStore("pop3"); // Try to connect to the server st.connect(host, user, pwd); } else { // Ssupports POP3 connection with SSL, the connection is established via SSL. String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //Properties pop3Props = new Properties(); prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); prop.setProperty("mail.pop3.socketFactory.fallback", "false"); prop.setProperty("mail.pop3.port", getRealSSLPort()); prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); st = new POP3SSLStore(sess, url); st.connect(); } log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //Open default folder INBOX Folder f = st.getFolder("INBOX"); f.open(Folder.READ_ONLY); if (f == null) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); } else { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder1.Label") + f.getName() + Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder2.Label") + f.getMessageCount()); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder1.Label") + f.getName() + Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder2.Label") + f.getNewMessageCount()); // Get emails Message msg_list[] = getPOPMessages(f, retrievemails); if (msg_list.length > 0) { List current_file_POP = new ArrayList(); List current_filepath_POP = new ArrayList(); int nb_email_POP = 1; DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy"); String startpattern = "name"; if (!Const.isEmpty(getRealFilenamePattern())) { startpattern = getRealFilenamePattern(); } for (int i = 0; i < msg_list.length; i++) { /*if(msg[i].isMimeType("text/plain")) { log.logDetailed(toString(), "Expediteur: "+msg[i].getFrom()[0]); log.logDetailed(toString(), "Sujet: "+msg[i].getSubject()); log.logDetailed(toString(), "Texte: "+(String)msg[i].getContent()); }*/ if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) { Message msg_POP = msg_list[i]; log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label") + msg_list[i].getFrom()[0]); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailSubject.Label") + msg_list[i].getSubject()); String localfilename_message = startpattern + "_" + dateFormat.format(new Date()) + "_" + (i + 1) + ".mail"; log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LocalFilename1.Label") + localfilename_message + Messages.getString("JobGetMailsFromPOP.LocalFilename2.Label")); File filename_message = new File(getRealOutputDirectory(), localfilename_message); OutputStream os_filename = new FileOutputStream(filename_message); Enumeration enums_POP = msg_POP.getAllHeaders(); while (enums_POP.hasMoreElements()) { Header header_POP = (Header) enums_POP.nextElement(); os_filename.write(new StringBuffer(header_POP.getName()).append(": ") .append(header_POP.getValue()).append("\r\n").toString().getBytes()); } os_filename.write("\r\n".getBytes()); InputStream in_POP = msg_POP.getInputStream(); byte[] buffer_POP = new byte[1024]; int length_POP = 0; while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) { os_filename.write(buffer_POP, 0, length_POP); } os_filename.close(); nb_email_POP++; current_file_POP.add(filename_message); current_filepath_POP.add(filename_message.getPath()); if (delete) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true); } } } } // Close and exit if (f != null) f.close(false); if (st != null) st.close(); f = null; st = null; sess = null; result.setNrErrors(0); result.setResult(true); } } } catch (NoSuchProviderException e) { log.logError(toString(), "provider error: " + e.getMessage()); } catch (MessagingException e) { log.logError(toString(), "Message error: " + e.getMessage()); } catch (Exception e) { log.logError(toString(), "Inexpected error: " + e.getMessage()); } finally { if (fileObject != null) { try { fileObject.close(); } catch (IOException ex) { } ; } sess = null; } return result; }
From source file:org.zilverline.core.IMAPCollection.java
/** * Index the given Collection./*from w w w . j a v a 2 s . com*/ * * @param fullIndex indicates whether a full or incremental index should be created * @throws IndexException if the Collections can not be indexed * @return true if succesfull */ private final boolean doIndex(boolean fullIndex) throws IndexException { IndexWriter writer = null; Store store = null; try { // record start time StopWatch watch = new StopWatch(); watch.start(); // make sure the index exists File indexDirectory = this.getIndexDirWithManagerDefaults(); // reindex if the index is not there or invalid boolean mustReindex = fullIndex; if (!this.isIndexValid()) { mustReindex = true; indexDirectory.mkdirs(); } // create an index(writer) writer = new IndexWriter(indexDirectory, this.createAnalyzer(), mustReindex); // see whether there are specific indexing settings in manager if (manager.getMergeFactor() != null) { writer.setMergeFactor(manager.getMergeFactor().intValue()); } if (manager.getMinMergeDocs() != null) { writer.setMaxBufferedDocs(manager.getMinMergeDocs().intValue()); } if (manager.getMaxMergeDocs() != null) { writer.setMaxMergeDocs(manager.getMaxMergeDocs().intValue()); } resetCache(fullIndex); // connect to IMAP log.debug("Connecting to IMAP server: " + host); Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props, null); store = session.getStore("imap"); log.debug("Connecting to " + host + " as " + user); store.connect(host, user, password); log.debug("Connected"); // start at the proper folder Folder topFolder = null; if (StringUtils.hasText(folder)) { topFolder = store.getFolder(folder); } else { topFolder = store.getDefaultFolder(); } indexFolder(writer, topFolder); // record end time and report duration of indexing watch.stop(); log.info("Indexed " + writer.docCount() + " documents in " + watch.elapsedTime()); return true; } catch (NoSuchProviderException e) { throw new IndexException("Can't connect to " + host, e); } catch (MessagingException e) { throw new IndexException("Error while accessing IMAP server " + host, e); } catch (IOException e) { throw new IndexException("Error indexing '" + this.getName() + "'. Possibly unable to remove old index", e); } catch (Exception e) { throw new IndexException("Error indexing '" + this.getName() + "'", e); } finally { if (writer != null) { try { writer.optimize(); log.debug("Optimizing index for " + name); writer.close(); log.debug("Closing index for " + name); } catch (IOException e1) { log.error("Error closing Index for " + name, e1); } } if (store != null) { try { store.close(); } catch (MessagingException e1) { log.error("Error closing IMAP server " + host, e1); } } init(); } }
From source file:com.sonicle.webtop.core.app.WebTopManager.java
private void createCyrusMailbox(String login, Store store) throws WTCyrusException { try {//from w w w . ja v a 2 s . c o m char sep = store.getDefaultFolder().getSeparator(); Folder c = store.getFolder("user" + sep + login); if (!c.exists()) c.create(Folder.HOLDS_FOLDERS); } catch (Exception exc) { throw new WTCyrusException(exc); } }
From source file:com.sonicle.webtop.core.app.WebTopManager.java
public void setCyrusAcl(String login, String acllogin, Store store) throws WTCyrusException { try {// w w w . ja v a 2 s. co m char sep = store.getDefaultFolder().getSeparator(); Folder f = store.getFolder("user" + sep + login); IMAPFolder folder = (IMAPFolder) f; Rights r = new Rights("lrswipcda"); ACL a = new ACL(acllogin, r); folder.addACL(a); } catch (Exception exc) { throw new WTCyrusException(exc); } }
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. j a v a 2 s . com 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.panet.imeta.job.entries.getpop.JobEntryGetPOP.java
@SuppressWarnings({ "unchecked" }) public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = previousResult; result.setResult(false);/* ww w .j a v a 2 s.c om*/ result.setNrErrors(1); //Get system properties Properties prop = new Properties(); prop.setProperty("mail.pop3s.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$ prop.setProperty("mail.pop3.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$ //Create session object Session sess = Session.getDefaultInstance(prop, null); sess.setDebug(true); FileObject fileObject = null; Store st = null; Folder f = null; try { int nbrmailtoretrieve = Const.toInt(firstmails, 0); String realOutputFolder = getRealOutputDirectory(); fileObject = KettleVFS.getFileObject(realOutputFolder); // Check if output folder exists if (!fileObject.exists()) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.FolderNotExists.Label", realOutputFolder)); //$NON-NLS-1$ } else { if (fileObject.getType() == FileType.FOLDER) { String host = getRealServername(); String user = getRealUsername(); String pwd = getRealPassword(); if (!getUseSSL()) { //Create POP3 object st = sess.getStore("pop3"); //$NON-NLS-1$ // Try to connect to the server st.connect(host, user, pwd); } else { // Ssupports POP3 connection with SSL, the connection is established via SSL. String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.fallback", "false"); //$NON-NLS-1$ //$NON-NLS-2$ prop.setProperty("mail.pop3.port", getRealSSLPort()); //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); //$NON-NLS-1$ URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); //$NON-NLS-1$ //$NON-NLS-2$ st = new POP3SSLStore(sess, url); st.connect(); } if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //$NON-NLS-1$ //Open the INBOX FOLDER // For POP3, the only folder available is the INBOX. f = st.getFolder("INBOX"); //$NON-NLS-1$ if (f == null) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); //$NON-NLS-1$ } else { // Open folder if (delete) f.open(Folder.READ_WRITE); else f.open(Folder.READ_ONLY); Message messageList[] = f.getMessages(); if (log.isDetailed()) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder.Label", f.getName(), //$NON-NLS-1$ String.valueOf(messageList.length))); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalUnreadMessagesFolder.Label", //$NON-NLS-1$ f.getName(), String.valueOf(f.getUnreadMessageCount()))); } // Get emails Message msg_list[] = getPOPMessages(f, retrievemails); if (msg_list.length > 0) { List<File> current_file_POP = new ArrayList<File>(); List<String> current_filepath_POP = new ArrayList<String>(); int nb_email_POP = 1; String startpattern = "name"; //$NON-NLS-1$ if (!Const.isEmpty(getRealFilenamePattern())) { startpattern = getRealFilenamePattern(); } for (int i = 0; i < msg_list.length; i++) { if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) { Message msg_POP = msg_list[i]; if (log.isDetailed()) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label", //$NON-NLS-1$ msg_list[i].getFrom()[0].toString())); log.logDetailed(toString(), Messages.getString( "JobGetMailsFromPOP.EmailSubject.Label", msg_list[i].getSubject())); //$NON-NLS-1$ } String localfilename_message = startpattern + "_" //$NON-NLS-1$ + StringUtil.getFormattedDateTimeNow(true) + "_" + (i + 1) + ".mail"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDetailed()) log.logDetailed(toString(), Messages.getString( "JobGetMailsFromPOP.LocalFilename.Label", localfilename_message)); //$NON-NLS-1$ File filename_message = new File(realOutputFolder, localfilename_message); OutputStream os_filename = new FileOutputStream(filename_message); Enumeration<Header> enums_POP = msg_POP.getAllHeaders(); while (enums_POP.hasMoreElements()) { Header header_POP = enums_POP.nextElement(); os_filename.write(new StringBuffer(header_POP.getName()).append(": ") //$NON-NLS-1$ .append(header_POP.getValue()).append("\r\n").toString().getBytes()); //$NON-NLS-1$ } os_filename.write("\r\n".getBytes()); //$NON-NLS-1$ InputStream in_POP = msg_POP.getInputStream(); byte[] buffer_POP = new byte[1024]; int length_POP = 0; while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) { os_filename.write(buffer_POP, 0, length_POP); } os_filename.close(); nb_email_POP++; current_file_POP.add(filename_message); current_filepath_POP.add(filename_message.getPath()); // Check attachments Object content = msg_POP.getContent(); if (content instanceof Multipart) { handleMultipart(realOutputFolder, (Multipart) content); } // Check if mail has to be deleted if (delete) { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); //$NON-NLS-1$ msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true); } } } } result.setNrErrors(0); result.setResult(true); } } else { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.Error.NotAFolder", realOutputFolder)); } } } catch (NoSuchProviderException e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.ProviderException", e.getMessage())); //$NON-NLS-1$ } catch (MessagingException e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.MessagingException", e.getMessage())); //$NON-NLS-1$ } catch (Exception e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.GeneralException", e.getMessage())); //$NON-NLS-1$ } finally { if (fileObject != null) { try { fileObject.close(); } catch (IOException ex) { } ; } //close the folder, passing in a true value to expunge the deleted message try { if (f != null) f.close(true); if (st != null) st.close(); } catch (Exception e) { log.logError(toString(), e.getMessage()); } // free memory f = null; st = null; sess = null; } return result; }
From source file:org.nuclos.server.ruleengine.RuleInterface.java
/** * * @param pop3Host//from w w w. j ava 2 s . c o m * @param pop3Port * @param pop3User * @param pop3Password * @param remove * @return * @throws NuclosFatalRuleException */ public List<NuclosMail> getMails(String pop3Host, String pop3Port, final String pop3User, final String pop3Password, boolean remove) throws NuclosFatalRuleException { try { Properties properties = new Properties(); properties.setProperty("mail.pop3.host", pop3Host); properties.setProperty("mail.pop3.port", pop3Port); properties.setProperty("mail.pop3.auth", "true"); properties.setProperty("mail.pop3.socketFactory.class", "javax.net.DefaultSocketFactory"); Session session = Session.getInstance(properties, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(pop3User, pop3Password); } }); session.setDebug(true); Store store = session.getStore("pop3"); store.connect(); Folder folder = store.getFolder("INBOX"); if (remove) { folder.open(Folder.READ_WRITE); } else { folder.open(Folder.READ_ONLY); } List<NuclosMail> result = new ArrayList<NuclosMail>(); Message message[] = folder.getMessages(); for (int i = 0; i < message.length; i++) { Message m = message[i]; NuclosMail mail = new NuclosMail(); logger.debug("Received mail: From: " + Arrays.toString(m.getFrom()) + "; To: " + Arrays.toString(m.getAllRecipients()) + "; ContentType: " + m.getContentType() + "; Subject: " + m.getSubject() + "; Sent: " + m.getSentDate()); Address[] senders = m.getFrom(); if (senders.length == 1 && senders[0] instanceof InternetAddress) { mail.setFrom(((InternetAddress) senders[0]).getAddress()); } else { mail.setFrom(Arrays.toString(m.getFrom())); } mail.setTo(Arrays.toString(m.getRecipients(RecipientType.TO))); mail.setSubject(m.getSubject()); if (m.isMimeType("text/plain")) { mail.setMessage((String) m.getContent()); } else { Multipart mp = (Multipart) m.getContent(); for (int j = 0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); MimeBodyPart mimePart = (MimeBodyPart) part; logger.debug( "Disposition: " + disposition + "; Part ContentType: " + mimePart.getContentType()); if (disposition == null && (mimePart.isMimeType("text/plain") || mimePart.isMimeType("text/html"))) { mail.setMessage((String) mimePart.getDataHandler().getContent()); } } getAttachments(mp, mail); } result.add(mail); if (remove) { m.setFlag(Flags.Flag.DELETED, true); } } if (remove) { folder.close(true); } else { folder.close(false); } store.close(); return result; } catch (Exception e) { throw new NuclosFatalRuleException(e); } }
From source file:org.nuxeo.ecm.platform.mail.utils.MailCoreHelper.java
protected static void doCheckMail(DocumentModel currentMailFolder, CoreSession coreSession) throws MessagingException { String email = (String) currentMailFolder.getPropertyValue(EMAIL_PROPERTY_NAME); String password = (String) currentMailFolder.getPropertyValue(PASSWORD_PROPERTY_NAME); if (!StringUtils.isEmpty(email) && !StringUtils.isEmpty(password)) { mailService = getMailService();/* w w w . java 2s . c o m*/ MessageActionPipe pipe = mailService.getPipe(PIPE_NAME); Visitor visitor = new Visitor(pipe); Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader()); // initialize context ExecutionContext initialExecutionContext = new ExecutionContext(); initialExecutionContext.put(MIMETYPE_SERVICE_KEY, getMimeService()); initialExecutionContext.put(PARENT_PATH_KEY, currentMailFolder.getPathAsString()); initialExecutionContext.put(CORE_SESSION_KEY, coreSession); initialExecutionContext.put(LEAVE_ON_SERVER_KEY, Boolean.TRUE); // TODO should be an attribute in 'protocol' // schema Folder rootFolder = null; Store store = null; try { String protocolType = (String) currentMailFolder.getPropertyValue(PROTOCOL_TYPE_PROPERTY_NAME); initialExecutionContext.put(PROTOCOL_TYPE_KEY, protocolType); // log.debug(PROTOCOL_TYPE_KEY + ": " + (String) initialExecutionContext.get(PROTOCOL_TYPE_KEY)); String host = (String) currentMailFolder.getPropertyValue(HOST_PROPERTY_NAME); String port = (String) currentMailFolder.getPropertyValue(PORT_PROPERTY_NAME); Boolean socketFactoryFallback = (Boolean) currentMailFolder .getPropertyValue(SOCKET_FACTORY_FALLBACK_PROPERTY_NAME); String socketFactoryPort = (String) currentMailFolder .getPropertyValue(SOCKET_FACTORY_PORT_PROPERTY_NAME); Boolean starttlsEnable = (Boolean) currentMailFolder .getPropertyValue(STARTTLS_ENABLE_PROPERTY_NAME); String sslProtocols = (String) currentMailFolder.getPropertyValue(SSL_PROTOCOLS_PROPERTY_NAME); Long emailsLimit = (Long) currentMailFolder.getPropertyValue(EMAILS_LIMIT_PROPERTY_NAME); long emailsLimitLongValue = emailsLimit == null ? EMAILS_LIMIT_DEFAULT : emailsLimit.longValue(); String imapDebug = Framework.getProperty(IMAP_DEBUG, "false"); Properties properties = new Properties(); properties.put("mail.store.protocol", protocolType); // properties.put("mail.host", host); // Is IMAP connection if (IMAP.equals(protocolType)) { properties.put("mail.imap.host", host); properties.put("mail.imap.port", port); properties.put("mail.imap.starttls.enable", starttlsEnable.toString()); properties.put("mail.imap.debug", imapDebug); properties.put("mail.imap.partialfetch", "false"); } else if (IMAPS.equals(protocolType)) { properties.put("mail.imaps.host", host); properties.put("mail.imaps.port", port); properties.put("mail.imaps.starttls.enable", starttlsEnable.toString()); properties.put("mail.imaps.ssl.protocols", sslProtocols); properties.put("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.imaps.socketFactory.fallback", socketFactoryFallback.toString()); properties.put("mail.imaps.socketFactory.port", socketFactoryPort); properties.put("mail.imap.partialfetch", "false"); properties.put("mail.imaps.partialfetch", "false"); } else if (POP3S.equals(protocolType)) { properties.put("mail.pop3s.host", host); properties.put("mail.pop3s.port", port); properties.put("mail.pop3s.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.pop3s.socketFactory.fallback", socketFactoryFallback.toString()); properties.put("mail.pop3s.socketFactory.port", socketFactoryPort); properties.put("mail.pop3s.ssl.protocols", sslProtocols); } else { // Is POP3 connection properties.put("mail.pop3.host", host); properties.put("mail.pop3.port", port); } properties.put("user", email); properties.put("password", password); Session session = Session.getInstance(properties); store = session.getStore(); store.connect(email, password); String folderName = INBOX; // TODO should be an attribute in 'protocol' schema rootFolder = store.getFolder(folderName); // need RW access to update message flags rootFolder.open(Folder.READ_WRITE); Message[] allMessages = rootFolder.getMessages(); // VDU log.debug("nbr of messages in folder:" + allMessages.length); FetchProfile fetchProfile = new FetchProfile(); fetchProfile.add(FetchProfile.Item.FLAGS); fetchProfile.add(FetchProfile.Item.ENVELOPE); fetchProfile.add(FetchProfile.Item.CONTENT_INFO); fetchProfile.add("Message-ID"); fetchProfile.add("Content-Transfer-Encoding"); rootFolder.fetch(allMessages, fetchProfile); if (rootFolder instanceof IMAPFolder) { // ((IMAPFolder)rootFolder).doCommand(FetchProfile) } List<Message> unreadMessagesList = new ArrayList<Message>(); for (Message message : allMessages) { Flags flags = message.getFlags(); int unreadMessagesListSize = unreadMessagesList.size(); if (flags != null && !flags.contains(Flag.SEEN) && unreadMessagesListSize < emailsLimitLongValue) { unreadMessagesList.add(message); if (unreadMessagesListSize == emailsLimitLongValue - 1) { break; } } } Message[] unreadMessagesArray = unreadMessagesList.toArray(new Message[unreadMessagesList.size()]); // perform email import visitor.visit(unreadMessagesArray, initialExecutionContext); // perform flag update globally Flags flags = new Flags(); flags.add(Flag.SEEN); boolean leaveOnServer = (Boolean) initialExecutionContext.get(LEAVE_ON_SERVER_KEY); if ((IMAP.equals(protocolType) || IMAPS.equals(protocolType)) && leaveOnServer) { flags.add(Flag.SEEN); } else { flags.add(Flag.DELETED); } rootFolder.setFlags(unreadMessagesArray, flags, true); } finally { if (rootFolder != null && rootFolder.isOpen()) { rootFolder.close(true); } if (store != null) { store.close(); } } } }