List of usage examples for javax.mail Folder getNewMessageCount
public synchronized int getNewMessageCount() throws MessagingException
From source file:uidmsgshow.java
public static void main(String argv[]) { long uid = -1; int optind;/*from w w w.j av a2 s. c o m*/ for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-f")) { mbox = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println( "Usage: uidmsgshow [-L url] [-T protocol] [-H host] [-U user] [-P password] [-f mailbox] [uid] [-v]"); System.exit(1); } else { break; } } try { if (optind < argv.length) uid = Long.parseLong(argv[optind]); // Get a Properties object Properties props = System.getProperties(); // Get a Session object Session session = Session.getInstance(props, null); // session.setDebug(true); // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Open the Folder Folder folder = store.getDefaultFolder(); if (folder == null) { System.out.println("No default folder"); System.exit(1); } folder = folder.getFolder(mbox); if (!folder.exists()) { System.out.println(mbox + " does not exist"); System.exit(1); } if (!(folder instanceof UIDFolder)) { System.out.println("This Provider or this folder does not support UIDs"); System.exit(1); } UIDFolder ufolder = (UIDFolder) folder; folder.open(Folder.READ_WRITE); int totalMessages = folder.getMessageCount(); if (totalMessages == 0) { System.out.println("Empty folder"); folder.close(false); store.close(); System.exit(1); } if (verbose) { int newMessages = folder.getNewMessageCount(); System.out.println("Total messages = " + totalMessages); System.out.println("New messages = " + newMessages); System.out.println("-------------------------------"); } if (uid == -1) { // Attributes & Flags for ALL messages .. Message[] msgs = ufolder.getMessagesByUID(1, UIDFolder.LASTUID); // Use a suitable FetchProfile FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(msgs, fp); for (int i = 0; i < msgs.length; i++) { System.out.println("--------------------------"); System.out.println("MESSAGE UID #" + ufolder.getUID(msgs[i]) + ":"); dumpEnvelope(msgs[i]); // dumpPart(msgs[i]); } } else { System.out.println("Getting message UID: " + uid); Message m = ufolder.getMessageByUID(uid); if (m != null) dumpPart(m); else System.out.println("This Message does not exist on this folder"); } folder.close(false); store.close(); } catch (Exception ex) { System.out.println("Oops, got exception! " + ex.getMessage()); ex.printStackTrace(); } System.exit(1); }
From source file:msgshow.java
public static void main(String argv[]) { int optind;//ww w . ja v a 2 s .c o m InputStream msgStream = System.in; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-D")) { debug = true; } else if (argv[optind].equals("-f")) { mbox = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-p")) { port = Integer.parseInt(argv[++optind]); } else if (argv[optind].equals("-s")) { showStructure = true; } else if (argv[optind].equals("-S")) { saveAttachments = true; } else if (argv[optind].equals("-m")) { showMessage = true; } else if (argv[optind].equals("-a")) { showAlert = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]"); System.out.println("\t[-P password] [-f mailbox] [msgnum ...] [-v] [-D] [-s] [-S] [-a]"); System.out.println("or msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]"); System.exit(1); } else { break; } } try { // Get a Properties object Properties props = System.getProperties(); // Get a Session object Session session = Session.getInstance(props, null); session.setDebug(debug); if (showMessage) { MimeMessage msg; if (mbox != null) msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox))); else msg = new MimeMessage(session, msgStream); dumpPart(msg); System.exit(0); } // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); if (showAlert) { store.addStoreListener(new StoreListener() { public void notification(StoreEvent e) { String s; if (e.getMessageType() == StoreEvent.ALERT) s = "ALERT: "; else s = "NOTICE: "; System.out.println(s + e.getMessage()); } }); } store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, port, user, password); else store.connect(); } // Open the Folder Folder folder = store.getDefaultFolder(); if (folder == null) { System.out.println("No default folder"); System.exit(1); } if (mbox == null) mbox = "INBOX"; folder = folder.getFolder(mbox); if (folder == null) { System.out.println("Invalid folder"); System.exit(1); } // 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 totalMessages = folder.getMessageCount(); if (totalMessages == 0) { System.out.println("Empty folder"); folder.close(false); store.close(); System.exit(1); } if (verbose) { int newMessages = folder.getNewMessageCount(); System.out.println("Total messages = " + totalMessages); System.out.println("New messages = " + newMessages); System.out.println("-------------------------------"); } if (optind >= argv.length) { // Attributes & Flags for all messages .. Message[] msgs = folder.getMessages(); // Use a suitable FetchProfile FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(msgs, fp); for (int i = 0; i < msgs.length; i++) { System.out.println("--------------------------"); System.out.println("MESSAGE #" + (i + 1) + ":"); dumpEnvelope(msgs[i]); // dumpPart(msgs[i]); } } else { while (optind < argv.length) { int msgnum = Integer.parseInt(argv[optind++]); System.out.println("Getting message number: " + msgnum); Message m = null; try { m = folder.getMessage(msgnum); dumpPart(m); } catch (IndexOutOfBoundsException iex) { System.out.println("Message number out of range"); } } } folder.close(false); store.close(); } catch (Exception ex) { System.out.println("Oops, got exception! " + ex.getMessage()); ex.printStackTrace(); System.exit(1); } System.exit(0); }
From source file:MainClass.java
public static void main(String argv[]) { int msgnum = -1; int optind;/* w ww . j a v a2 s.c om*/ InputStream msgStream = System.in; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-D")) { debug = true; } else if (argv[optind].equals("-f")) { mbox = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-p")) { port = Integer.parseInt(argv[++optind]); } else if (argv[optind].equals("-s")) { showStructure = true; } else if (argv[optind].equals("-S")) { saveAttachments = true; } else if (argv[optind].equals("-m")) { showMessage = true; } else if (argv[optind].equals("-a")) { showAlert = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]"); System.out.println("\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]"); System.out.println("or msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]"); System.exit(1); } else { break; } } try { if (optind < argv.length) msgnum = Integer.parseInt(argv[optind]); // Get a Properties object Properties props = System.getProperties(); // Get a Session object Session session = Session.getInstance(props, null); session.setDebug(debug); if (showMessage) { MimeMessage msg; if (mbox != null) msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox))); else msg = new MimeMessage(session, msgStream); dumpPart(msg); System.exit(0); } // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); if (showAlert) { store.addStoreListener(new StoreListener() { public void notification(StoreEvent e) { String s; if (e.getMessageType() == StoreEvent.ALERT) s = "ALERT: "; else s = "NOTICE: "; System.out.println(s + e.getMessage()); } }); } store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, port, user, password); else store.connect(); } // Open the Folder Folder folder = store.getDefaultFolder(); if (folder == null) { System.out.println("No default folder"); System.exit(1); } if (mbox == null) mbox = "INBOX"; folder = folder.getFolder(mbox); if (folder == null) { System.out.println("Invalid folder"); System.exit(1); } // 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 totalMessages = folder.getMessageCount(); if (totalMessages == 0) { System.out.println("Empty folder"); folder.close(false); store.close(); System.exit(1); } if (verbose) { int newMessages = folder.getNewMessageCount(); System.out.println("Total messages = " + totalMessages); System.out.println("New messages = " + newMessages); System.out.println("-------------------------------"); } if (msgnum == -1) { // Attributes & Flags for all messages .. Message[] msgs = folder.getMessages(); // Use a suitable FetchProfile FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(msgs, fp); for (int i = 0; i < msgs.length; i++) { System.out.println("--------------------------"); System.out.println("MESSAGE #" + (i + 1) + ":"); dumpEnvelope(msgs[i]); // dumpPart(msgs[i]); } } else { System.out.println("Getting message number: " + msgnum); Message m = null; try { m = folder.getMessage(msgnum); dumpPart(m); } catch (IndexOutOfBoundsException iex) { System.out.println("Message number out of range"); } } folder.close(false); store.close(); } catch (Exception ex) { System.out.println("Oops, got exception! " + ex.getMessage()); ex.printStackTrace(); System.exit(1); } System.exit(0); }
From source file:folderlist.java
static void dumpFolder(Folder folder, boolean recurse, String tab) throws Exception { System.out.println(tab + "Name: " + folder.getName()); System.out.println(tab + "Full Name: " + folder.getFullName()); System.out.println(tab + "URL: " + folder.getURLName()); if (verbose) { if (!folder.isSubscribed()) System.out.println(tab + "Not Subscribed"); if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) { if (folder.hasNewMessages()) System.out.println(tab + "Has New Messages"); System.out.println(tab + "Total Messages: " + folder.getMessageCount()); System.out.println(tab + "New Messages: " + folder.getNewMessageCount()); System.out.println(tab + "Unread Messages: " + folder.getUnreadMessageCount()); }//from www. ja v a2 s . c o m if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) System.out.println(tab + "Is Directory"); /* * Demonstrate use of IMAP folder attributes * returned by the IMAP LIST response. */ if (folder instanceof IMAPFolder) { IMAPFolder f = (IMAPFolder) folder; String[] attrs = f.getAttributes(); if (attrs != null && attrs.length > 0) { System.out.println(tab + "IMAP Attributes:"); for (int i = 0; i < attrs.length; i++) System.out.println(tab + " " + attrs[i]); } } } System.out.println(); if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) { if (recurse) { Folder[] f = folder.list(); for (int i = 0; i < f.length; i++) dumpFolder(f[i], recurse, tab + " "); } } }
From source file:MainClass.java
static void dumpFolder(Folder folder, boolean recurse, String tab) throws Exception { System.out.println(tab + "Name: " + folder.getName()); System.out.println(tab + "Full Name: " + folder.getFullName()); System.out.println(tab + "URL: " + folder.getURLName()); if (verbose) { if (!folder.isSubscribed()) System.out.println(tab + "Not Subscribed"); if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) { if (folder.hasNewMessages()) System.out.println(tab + "Has New Messages"); System.out.println(tab + "Total Messages: " + folder.getMessageCount()); System.out.println(tab + "New Messages: " + folder.getNewMessageCount()); System.out.println(tab + "Unread Messages: " + folder.getUnreadMessageCount()); }//from w ww . j a v a2s .co m if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) System.out.println(tab + "Is Directory"); /* * Demonstrate use of IMAP folder attributes returned by the IMAP LIST * response. */ if (folder instanceof IMAPFolder) { IMAPFolder f = (IMAPFolder) folder; String[] attrs = f.getAttributes(); if (attrs != null && attrs.length > 0) { System.out.println(tab + "IMAP Attributes:"); for (int i = 0; i < attrs.length; i++) System.out.println(tab + " " + attrs[i]); } } } System.out.println(); if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) { if (recurse) { Folder[] f = folder.list(); for (int i = 0; i < f.length; i++) dumpFolder(f[i], recurse, tab + " "); } } }
From source file:be.ibridge.kettle.job.entry.getpop.JobEntryGetPOP.java
public Message[] getPOPMessages(Folder folder, int retrievemails) throws Exception { // Get messages .. try {//from w w w . j a v a 2s. co m int newMsgs = folder.getNewMessageCount(); int msgCount = folder.getMessageCount(); Message msgsAll[] = folder.getMessages(); if (retrievemails == 1) { Message msgsNew[] = folder.getMessages(msgCount - newMsgs + 1, msgCount); return (msgsNew); } else { return (msgsAll); } } catch (Exception e) { return null; } }
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 va 2 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:net.wastl.webmail.server.WebMailSession.java
/** * Create a Message List./*from ww w . j a v a2 s . co m*/ * Fetches a list of headers in folder foldername for part list_part. * The messagelist will be stored in the "MESSAGES" environment. * * @param foldername folder for which a message list should be built * @param list_part part of list to display (1 = last xx messages, 2 = total-2*xx - total-xx messages) */ public void createMessageList(String folderhash, int list_part) throws NoSuchFolderException { long time_start = System.currentTimeMillis(); TimeZone tz = TimeZone.getDefault(); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, user.getPreferredLocale()); df.setTimeZone(tz); try { Folder folder = getFolder(folderhash); Element xml_folder = model.getFolder(folderhash); Element xml_current = model.setCurrentFolder(folderhash); Element xml_messagelist = model.getMessageList(xml_folder); if (folder == null) { throw new NoSuchFolderException(folderhash); } long fetch_start = System.currentTimeMillis(); if (!folder.isOpen()) { folder.open(Folder.READ_ONLY); } else { folder.close(false); folder.open(Folder.READ_ONLY); } /* Calculate first and last message to show */ int total_messages = folder.getMessageCount(); int new_messages = folder.getNewMessageCount(); int show_msgs = user.getMaxShowMessages(); xml_messagelist.setAttribute("total", total_messages + ""); xml_messagelist.setAttribute("new", new_messages + ""); log.debug("Total: " + total_messages); /* Handle small messagelists correctly */ if (total_messages < show_msgs) { show_msgs = total_messages; } /* Don't accept list-parts smaller than 1 */ if (list_part < 1) { list_part = 1; } for (int k = 0; k < list_part; k++) { total_messages -= show_msgs; } /* Handle beginning of message list */ if (total_messages < 0) { total_messages = 0; } int first = total_messages + 1; int last = total_messages + show_msgs; /* Set environment variable */ setEnv(); xml_current.setAttribute("first_msg", first + ""); xml_current.setAttribute("last_msg", last + ""); xml_current.setAttribute("list_part", list_part + ""); /* Fetch headers */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.CONTENT_INFO); log.debug("Last: " + last + ", first: " + first); Message[] msgs = folder.getMessages(first, last); log.debug(msgs.length + " messages fetching..."); folder.fetch(msgs, fp); long fetch_stop = System.currentTimeMillis(); Map header = new Hashtable(15); Flags.Flag[] sf; String from, to, cc, bcc, replyto, subject; String messageid; for (int i = msgs.length - 1; i >= 0; i--) { // if(((MimeMessage)msgs[i]).getMessageID() == null) { // folder.close(false); // folder.open(Folder.READ_WRITE); // ((MimeMessage)msgs[i]).setHeader("Message-ID","<"+user.getLogin()+"."+System.currentTimeMillis()+".jwebmail@"+user.getDomain()+">"); // ((MimeMessage)msgs[i]).saveChanges(); // folder.close(false); // folder.open(Folder.READ_ONLY); // } try { StringTokenizer tok = new StringTokenizer(((MimeMessage) msgs[i]).getMessageID(), "<>"); messageid = tok.nextToken(); } catch (NullPointerException ex) { // For mail servers that don't generate a Message-ID (Outlook et al) messageid = user.getLogin() + "." + i + ".jwebmail@" + user.getDomain(); } XMLMessage xml_message = model.getMessage(xml_folder, msgs[i].getMessageNumber() + "", messageid); /* Addresses */ from = ""; replyto = ""; to = ""; cc = ""; bcc = ""; try { from = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getFrom())); } catch (UnsupportedEncodingException e) { from = Helper.joinAddress(msgs[i].getFrom()); } try { replyto = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getReplyTo())); } catch (UnsupportedEncodingException e) { replyto = Helper.joinAddress(msgs[i].getReplyTo()); } try { to = MimeUtility .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO))); } catch (UnsupportedEncodingException e) { to = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO)); } try { cc = MimeUtility .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC))); } catch (UnsupportedEncodingException e) { cc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC)); } try { bcc = MimeUtility .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC))); } catch (UnsupportedEncodingException e) { bcc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC)); } if (from == "") from = getStringResource("unknown sender"); if (to == "") to = getStringResource("unknown recipient"); /* Flags */ sf = msgs[i].getFlags().getSystemFlags(); String basepath = parent.getBasePath(); for (int j = 0; j < sf.length; j++) { if (sf[j] == Flags.Flag.RECENT) xml_message.setAttribute("recent", "true"); if (sf[j] == Flags.Flag.SEEN) xml_message.setAttribute("seen", "true"); if (sf[j] == Flags.Flag.DELETED) xml_message.setAttribute("deleted", "true"); if (sf[j] == Flags.Flag.ANSWERED) xml_message.setAttribute("answered", "true"); if (sf[j] == Flags.Flag.DRAFT) xml_message.setAttribute("draft", "true"); if (sf[j] == Flags.Flag.FLAGGED) xml_message.setAttribute("flagged", "true"); if (sf[j] == Flags.Flag.USER) xml_message.setAttribute("user", "true"); } if (msgs[i] instanceof MimeMessage && ((MimeMessage) msgs[i]).getContentType().toUpperCase().startsWith("MULTIPART/")) { xml_message.setAttribute("attachment", "true"); } if (msgs[i] instanceof MimeMessage) { int size = ((MimeMessage) msgs[i]).getSize(); size /= 1024; xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB"); } /* Subject */ subject = ""; if (msgs[i].getSubject() != null) { try { subject = MimeUtility.decodeText(msgs[i].getSubject()); } catch (UnsupportedEncodingException ex) { subject = msgs[i].getSubject(); log.warn("Unsupported Encoding: " + ex.getMessage()); } } if (subject == null || subject.equals("")) { subject = getStringResource("no subject"); } /* Set all of what we found into the DOM */ xml_message.setHeader("FROM", from); try { // hmm, why decode subject twice? Though it doesn't matter.. xml_message.setHeader("SUBJECT", MimeUtility.decodeText(subject)); } catch (UnsupportedEncodingException e) { xml_message.setHeader("SUBJECT", subject); log.warn("Unsupported Encoding: " + e.getMessage()); } xml_message.setHeader("TO", to); xml_message.setHeader("CC", cc); xml_message.setHeader("BCC", bcc); xml_message.setHeader("REPLY-TO", replyto); /* Date */ Date d = msgs[i].getSentDate(); String ds = ""; if (d != null) { ds = df.format(d); } xml_message.setHeader("DATE", ds); } long time_stop = System.currentTimeMillis(); // try { // XMLCommon.writeXML(model.getRoot(),new FileOutputStream("/tmp/wmdebug"),""); // } catch(IOException ex) {} log.debug("Construction of message list took " + (time_stop - time_start) + " ms. Time for IMAP transfer was " + (fetch_stop - fetch_start) + " ms."); folder.close(false); } catch (NullPointerException e) { log.error("Failed to construct message list", e); throw new NoSuchFolderException(folderhash); } catch (MessagingException ex) { log.error("Failed to construct message list. " + "For some reason, contuing anyways.", ex); } }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Construct the folder subtree for the given folder and append it to * xml_parent.//from www.ja v a 2 s . c o m * * N.b. this method does not necessarily create a new XML Folder Element. * If called with subscribed_only and the target Folder (and in some * cases its descendants) are not subscribed, no Element will be created * and 0 will be returned. * <P> * Pop servers don't support nesting at all, so you'll just get a single * level out of this method. * <P> * There is a critical subscribed_only difference in behavior between * Maildir and mbox type mail servers. * Maildir folders are all HOLDS_MESSAGES, whether empty or not, and * these folders have a subscribed attribute which the user can set, * and which we honor. * mbox folders, on the other hand, have no subscribed attribute for * their !HOLDS_MESSAGE folders, so we must recurse to all of the * descendant HOLDS_MESSAGE folders to see if we should show. * * @param folder the folder where we begin * @param xml_parent XML Element where the gathered information will be * appended * @param subscribed_only Only add 'subscribed' folders * @param doCount Whether to generate message counts for Elements * corresponding to HOLDS_MESSAGE folders. * @returns maximum depth of the folder tree (needed to calculate the * necessary columns in a table). Returns 0 if no XML elements added. */ protected int getFolderTree(Folder folder, Element xml_parent, boolean subscribed_only, boolean doCount) { int generatedDepth = 0; int folderType; Element xml_folder; try { folderType = folder.getType(); } catch (MessagingException ex) { log.error("Can't get enough info from server to even make Gui node", ex); xml_parent.setAttribute("error", "For child '" + folder.getName() + ": " + ex.getMessage()); return 0; } boolean holds_folders = (folderType & Folder.HOLDS_FOLDERS) != 0; boolean holds_messages = (folderType & Folder.HOLDS_MESSAGES) != 0; // Sanity check: if ((!holds_folders) && !holds_messages) { log.fatal("Folder can hold neither folders nor messages: " + folder.getFullName()); throw new RuntimeException("Folder can hold neither folders nor messages: " + folder.getFullName()); } if (subscribed_only && holds_messages && !folder.isSubscribed()) return generatedDepth; // Return right away and save a LOT OF WORK // N.b. we honor folder.isSubscribed() only for holds_message // folders. That means all Maildir server folders, and all // mbox server folders except for mbox directories. In this // last case, we must recurse to determine whether to show folder. String id = generateFolderHash(folder); xml_folder = model.createFolder(id, folder.getName(), holds_folders, holds_messages); // XMLUserModel.createFolder() declares no throws. If any Exceptions // are expected from it, move the statement above into the try block. // The xml_folder Element here will be orphaned and GC'd if we don't // appendChild (in which case we return 0). if (doCount && holds_messages) try { // this folder will definitely be added! /* This folder can contain messages */ Element messagelist = model.createMessageList(); int total_messages = folder.getMessageCount(); int new_messages = folder.getNewMessageCount(); if (total_messages == -1 || new_messages == -1 || !folder.isOpen()) { folder.open(Folder.READ_ONLY); total_messages = folder.getMessageCount(); new_messages = folder.getNewMessageCount(); } if (folder.isOpen()) folder.close(false); messagelist.setAttribute("total", total_messages + ""); messagelist.setAttribute("new", new_messages + ""); log.debug("Counted " + new_messages + '/' + total_messages + " for folder " + folder.getFullName()); xml_folder.appendChild(messagelist); } catch (MessagingException ex) { log.warn("Failed to count messages in folder '" + folder.getFullName() + "'", ex); xml_folder.setAttribute("error", ex.getMessage()); } int descendantDepth = 0; if (holds_folders) try { Set<String> fullNameSet = new HashSet<String>(); /* Recursively add subfolders to the XML model */ // DO NOT USE listSubscribed(), because with !HOLDS_MESSAGE // folders, that skips non-Message Folders which may contain // subscribed descendants! for (Folder f : folder.list()) { if (!fullNameSet.add(f.getFullName())) { log.warn("Skipping duplicate subfolder returned by mail" + " server: " + f.getFullName()); continue; } if (subscribed_only && (f.getType() & Folder.HOLDS_MESSAGES) != 0 && !f.isSubscribed()) continue; /* If we recursed here, the getFolderTree() would * just return 0 and no harm done. * Just helping performance by preventing a recursion * here. * For comment on the logic here, see the same test * towards the top of this method (before recursion). */ int depth = getFolderTree(f, xml_folder, subscribed_only, doCount); if (depth > descendantDepth) descendantDepth = depth; } generatedDepth += descendantDepth; } catch (MessagingException ex) { xml_folder.setAttribute("error", ex.getMessage()); } // We've already validated that if subscribed_only and holds_message // then folder is subcribed. Also verified either holds_m or holds_f. // Only have to check the !holds_message case. if (subscribed_only && (!holds_messages) && descendantDepth < 1) { xml_folder = null; // Unnecessary, but may encourage GC return generatedDepth; } /* We ALWAYS return only subscribed folders except for these two * distinct cases: */ xml_folder.setAttribute("subscribed", ((holds_messages && !folder.isSubscribed()) || ((!holds_messages) && descendantDepth < 1)) ? "false" : "true"); // N.b. our Element's "subscribed" element does not correspond 1:1 // to Folder.isSubscribed(), since non-message-holding Folders have // no "subscribed" attribute. folders.put(id, folder); xml_parent.appendChild(xml_folder); generatedDepth++; // Add the count for xml_folder return generatedDepth; }
From source file:net.wastl.webmail.server.WebMailSession.java
public void refreshFolderInformation(String folderhash) { Folder folder = getFolder(folderhash); Element xml_folder = model.getFolder(folderhash); if (xml_folder.getAttribute("holds_messages").toLowerCase().equals("true")) { try {/*w w w . j a v a2 s . co m*/ Element messagelist = model.createMessageList(); int total_messages = folder.getMessageCount(); int new_messages = folder.getNewMessageCount(); if ((total_messages == -1 || new_messages == -1) && !folder.isOpen()) { folder.open(Folder.READ_ONLY); total_messages = folder.getMessageCount(); new_messages = folder.getNewMessageCount(); } if (folder.isOpen()) folder.close(false); messagelist.setAttribute("total", total_messages + ""); messagelist.setAttribute("new", new_messages + ""); model.removeMessageList(xml_folder); xml_folder.appendChild(messagelist); } catch (MessagingException ex) { xml_folder.setAttribute("error", ex.getMessage()); } } }