List of usage examples for javax.mail Folder READ_ONLY
int READ_ONLY
To view the source code for javax.mail Folder READ_ONLY.
Click Source Link
From source file:com.szmslab.quickjavamail.receive.MailReceiver.java
/** * ????// w ww . j a va 2 s.c om * * @param callback * ??1??? * @throws Exception */ public void execute(ReceiveIterationCallback callback) throws Exception { final Session session = useDefaultSession ? Session.getDefaultInstance(properties.getProperties(), properties.getAuthenticator()) : Session.getInstance(properties.getProperties(), properties.getAuthenticator()); session.setDebug(isDebug); Store store = null; Folder folder = null; try { store = session.getStore(properties.getProtocol()); store.connect(); folder = store.getFolder(folderName); folder.open(readonly ? Folder.READ_ONLY : Folder.READ_WRITE); final Message messages[] = folder.getMessages(); for (Message message : messages) { MessageLoader loader = new MessageLoader(message, !readonly); boolean isContinued = callback.iterate(loader); if (!readonly && loader.isDeleted()) { message.setFlag(Flags.Flag.DELETED, loader.isDeleted()); } if (!isContinued) { break; } } } finally { if (folder != null) { try { folder.close(!readonly); } catch (MessagingException e) { System.out.println(e); } } if (store != null) { try { store.close(); } catch (MessagingException e) { System.out.println(e); } } } }
From source file:org.apache.hupa.server.servlet.DownloadAttachmentServlet.java
/** * Handle to write back the requested attachment *///from w w w.j a va 2 s . c o m @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User user = (User) request.getSession().getAttribute(SConsts.USER_SESS_ATTR); if (user == null) throw new ServletException("Invalid session"); String message_uuid = request.getParameter(SConsts.PARAM_UID); String attachmentName = request.getParameter(SConsts.PARAM_NAME); String folderName = request.getParameter(SConsts.PARAM_FOLDER); String mode = request.getParameter(SConsts.PARAM_MODE); boolean inline = "inline".equals(mode); if (!inline) { response.setHeader("Content-disposition", "attachment; filename=" + attachmentName + ""); } InputStream in = null; OutputStream out = response.getOutputStream(); IMAPFolder folder = null; try { Store store = cache.get(user); folder = (IMAPFolder) store.getFolder(folderName); if (folder.isOpen() == false) { folder.open(Folder.READ_ONLY); } Message m = folder.getMessageByUID(Long.parseLong(message_uuid)); Object content = m.getContent(); Part part = MessageUtils.handleMultiPart(logger, content, attachmentName); if (part.getContentType() != null) { response.setContentType(part.getContentType()); } else { response.setContentType("application/download"); } handleAttachmentData(request, m, attachmentName, part.getInputStream(), out); return; } catch (Exception e) { logger.error("Error while downloading attachment " + attachmentName + " of message " + message_uuid + " for user " + user.getName(), e); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); if (folder != null) { try { folder.close(false); } catch (MessagingException e) { } } } }
From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java
/** * {@inheritDoc}/*from w ww . j av a 2 s.c o m*/ * * @throws MessagingException * @see org.xwiki.contrib.mail.IMailReader#readFromStore(java.lang.String) */ public Message read(String folder, String messageid) throws MessagingException { Store store = getJavamailStore(); store.connect(); Folder mailFolder = store.getDefaultFolder().getFolder(folder); mailFolder.open(Folder.READ_ONLY); Message[] messages = mailFolder.search(new MessageIDTerm(messageid)); mailFolder.close(false); store.close(); if (messages.length > 0) { return messages[0]; } return null; }
From source file:server.MailPop3Expert.java
@Override public void run() { //obtengo la agenda List<String> agenda = XmlParcerExpert.getInstance().getAgenda(); while (store.isConnected()) { try {/*from w w w .j ava 2s . co m*/ // Abre la carpeta INBOX Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_ONLY); // Obtiene los mails Message[] arrayMessages = folderInbox.getMessages(); //procesa los mails for (int i = 0; i < arrayMessages.length; i++) { Message message = arrayMessages[i]; Address[] fromAddress = message.getFrom(); String from = fromAddress[0].toString(); String subject = message.getSubject(); String sentDate = message.getSentDate().toString(); String messageContent = ""; String contentType = message.getContentType(); if (contentType.contains("multipart")) { // Si el contenido es mulpart Multipart multiPart = (Multipart) message.getContent(); int numberOfParts = multiPart.getCount(); for (int partCount = 0; partCount < numberOfParts; partCount++) { MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount); if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { // si contiene un archivo } else { // el contenido del mensaje messageContent = part.getContent().toString(); } } } else if (contentType.contains("text/plain") || contentType.contains("text/html")) { Object content = message.getContent(); if (content != null) { messageContent = content.toString(); } } //parseo del from if (from.contains("<")) { from = from.substring(from.indexOf("<") + 1, from.length() - 1); } //si esta en la agenda if (agenda.contains(from)) { //obtiene la trama try { messageContent = messageContent.substring(messageContent.indexOf(">"), messageContent.indexOf("<") + 4); if (messageContent.startsWith(">") && messageContent.endsWith("<")) { //procesa el mail XmlParcerExpert.getInstance().processAndSaveMail(from, messageContent); frame.loadMails(); } } catch (Exception e) { e.printStackTrace(); } } else { //no lo guarda } } folderInbox.close(false); //duerme el hilo por el tiempo de la frecuencia Thread.sleep(frecuency * 60 * 1000); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException ex) { //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex); } catch (MessagingException ex) { //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:EmailBean.java
private void handleMessages(HttpServletRequest request, PrintWriter out) throws IOException, ServletException { HttpSession httpSession = request.getSession(); String user = (String) httpSession.getAttribute("user"); String password = (String) httpSession.getAttribute("pass"); String popAddr = (String) httpSession.getAttribute("pop"); Store popStore = null;//from ww w . jav a 2s. co m Folder folder = null; if (!check(popAddr)) popAddr = EmailBean.DEFAULT_SERVER; try { if ((!check(user)) || (!check(password))) throw new ServletException("A valid username and password is required to check email."); Properties properties = System.getProperties(); Session session = Session.getDefaultInstance(properties); popStore = session.getStore("pop3"); popStore.connect(popAddr, user, password); folder = popStore.getFolder("INBOX"); if (!folder.exists()) throw new ServletException("An 'INBOX' folder does not exist for the user."); folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); int msgLen = messages.length; if (msgLen == 0) out.println("<h2>The INBOX folder does not yet contain any email messages.</h2>"); for (int i = 0; i < msgLen; i++) { displayMessage(messages[i], out); out.println("<br /><br />"); } } catch (Exception exc) { out.println("<h2>Sorry, an error occurred while accessing the email messages.</h2>"); out.println(exc.toString()); } finally { try { if (folder != null) folder.close(false); if (popStore != null) popStore.close(); } catch (Exception e) { } } }
From source file:org.openhealthtools.openatna.net.MailConnection.java
public Message[] retrieveAllMessages() throws MessagingException { Message messages[] = null;//from w ww. ja va 2 s . c o m if (store != null && pop3 != null) { if (inbox == null) { store.connect(pop3.getValue("HOSTNAME"), pop3.getValue("USERNAME"), pop3.getValue("PASSWORD")); inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); } messages = inbox.getMessages(); } else { log.error("Store and pop3 must be set before retrieving messages."); throw new MessagingException("Attempt to retrieve from invalid pop3 connection."); } return messages; }
From source file:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java
private void readMessagesFolder(Folder folder) throws MessagingException, IOException, SearchLibException { folder.open(Folder.READ_ONLY); String folderFullName = folder.getFullName(); try {/*from w w w . j a va2s . c om*/ int max = folder.getMessageCount(); int i = 0; final int buffer = item.getBufferSize(); while (i < max && !thread.isAborted()) { thread.setStatusInfo(CrawlStatus.CRAWL); int end = i + buffer; if (end > max) end = max; Message[] messages = folder.getMessages(i + 1, end); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); folder.fetch(messages, fp); for (Message message : messages) { if (thread.isAborted()) break; i++; String messageId = getMessageId(folder, message); if (StringUtils.isEmpty(messageId)) continue; if (thread.isAlreadyIndexed(messageId)) { thread.incIgnored(); continue; } IndexDocument crawlIndexDocument = new IndexDocument(item.getLang()); IndexDocument parserIndexDocument = new IndexDocument(item.getLang()); crawlIndexDocument.addString(MailboxFieldEnum.folder.name(), folderFullName); try { readMessage(crawlIndexDocument, parserIndexDocument, folder, message, messageId); thread.addDocument(crawlIndexDocument, parserIndexDocument); } catch (Exception e) { Logging.warn(e); thread.incError(); } } } } finally { folder.close(false); } }
From source file:com.seleniumtests.connectors.mails.ImapClient.java
/** * get list of all emails in folder//from ww w.j a v a2 s.c om * * @param folderName folder to read * @param firstMessageTime date from which we should get messages * @param firstMessageIndex index of the firste message to find * @throws MessagingException * @throws IOException */ @Override public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime) throws MessagingException, IOException { if (folderName == null) { throw new MessagingException("folder ne doit pas tre vide"); } // Get folder Folder folder = store.getFolder(folderName); folder.open(Folder.READ_ONLY); // Get directory Message[] messages = folder.getMessages(); List<Message> preFilteredMessages = new ArrayList<>(); final LocalDateTime firstTime = firstMessageTime; // on filtre les message en fonction du mode de recherche if (searchMode == SearchMode.BY_INDEX || firstTime == null) { for (int i = firstMessageIndex, n = messages.length; i < n; i++) { preFilteredMessages.add(messages[i]); } } else { preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() { private static final long serialVersionUID = 1L; @Override public boolean match(Message msg) { try { return !msg.getReceivedDate() .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant())); } catch (MessagingException e) { return false; } } })); } List<Email> filteredEmails = new ArrayList<>(); lastMessageIndex = messages.length; for (Message message : preFilteredMessages) { String contentType = ""; try { contentType = message.getContentType(); } catch (MessagingException e) { MimeMessage msg = (MimeMessage) message; message = new MimeMessage(msg); contentType = message.getContentType(); } // decode content String messageContent = ""; List<String> attachments = new ArrayList<>(); if (contentType.toLowerCase().contains("text/html")) { messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString()); } else if (contentType.toLowerCase().contains("multipart/")) { List<BodyPart> partList = getMessageParts((Multipart) message.getContent()); // store content in list for (BodyPart part : partList) { String partContentType = part.getContentType().toLowerCase(); if (partContentType.contains("text/html")) { messageContent = messageContent .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString())); } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) { messageContent = messageContent.concat((String) part.getContent().toString()); } else if (partContentType.contains("image") || partContentType.contains("application/") || partContentType.contains("text/x-vcard")) { if (part.getFileName() != null) { attachments.add(part.getFileName()); } else { attachments.add(part.getDescription()); } } else { logger.debug("type: " + part.getContentType()); } } } // create a new email filteredEmails.add(new Email(message.getSubject(), messageContent, "", message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(), attachments)); } folder.close(false); return filteredEmails; }
From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java
/** * Returns new messages and fetches details for each message. *///from ww w . j a v a 2s . c o m @Transactional(readOnly = false) public ResultClass<Boolean> downloadEmails() { ResultClass<Boolean> result = new ResultClass<>(); Properties properties = getServerProperties(protocol, host, port); Session session = Session.getDefaultInstance(properties); try { // connects to the message store Store store = session.getStore(protocol); store.connect(userName, password); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_ONLY); // fetches new messages from server Message[] messages = folderInbox.getMessages(); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; String[] idHeaders = msg.getHeader("MESSAGE-ID"); if (idHeaders != null && idHeaders.length > 0) { MessageBox exists = repositoryMailBox.getMessageBox(idHeaders[0]); if (exists == null) { MessageBox messageBox = new MessageBox(); messageBox.setSubject(msg.getSubject()); messageBox.setCode(idHeaders[0]); Address[] fromAddresses = msg.getFrom(); String from = InternetAddress.toString(fromAddresses); if (from.startsWith("=?")) { from = MimeUtility.decodeWord(from); } messageBox.setFrom(from); String to = InternetAddress.toString(msg.getRecipients(RecipientType.TO)); if (to.startsWith("=?")) { to = MimeUtility.decodeWord(to); } messageBox.setTo(to); String[] replyHeaders = msg.getHeader("References"); if (replyHeaders != null && replyHeaders.length > 0) { StringTokenizer tokens = new StringTokenizer(replyHeaders[0]); MessageBox parent = repositoryMailBox.getMessageBox(tokens.nextToken()); if (parent != null) parent.addReply(messageBox); } result = parseSubjectAndCreate(messageBox, msg); } } } folderInbox.close(false); store.close(); return result; } catch (NoSuchProviderException ex) { logger.error("No provider for protocol: " + protocol); ex.printStackTrace(); } catch (MessagingException ex) { logger.error("Could not connect to the message store"); ex.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } result.setSingleElement(false); return result; }
From source file:com.intranet.intr.inbox.EmpControllerInbox.java
public int numCorreosNOL(String name) { int numMensa = 0; Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); try {/*w ww .j a v a 2s . co m*/ users u = usuarioService.getByLogin(name); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna()); System.out.println("ola" + store); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); Message msg[] = inbox.search(ft); System.out.println("MAILS: " + msg.length); System.out.println(" " + msg.length); numMensa = msg.length; } catch (Exception ex) { } return numMensa; }