List of usage examples for javax.mail Folder isOpen
public abstract boolean isOpen();
From source file:com.cws.esolutions.core.utils.EmailUtils.java
/** * Processes and sends an email message as generated by the requesting * application. This method is utilized with a JNDI datasource. * * @param dataSource - The email message * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise * @param authList - If authRequired is true, this must be populated with the auth info * @return List - The list of email messages in the mailstore * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing *///from ww w. ja v a 2s . co m public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException { final String methodName = EmailUtils.CNAME + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("dataSource: {}", dataSource); DEBUGGER.debug("authRequired: {}", authRequired); DEBUGGER.debug("authList: {}", authList); } Folder mailFolder = null; Session mailSession = null; Folder archiveFolder = null; List<EmailMessage> emailMessages = null; Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, -24); final Long TIME_PERIOD = cal.getTimeInMillis(); final URLName URL_NAME = (authRequired) ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1)) : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, null, null); if (DEBUG) { DEBUGGER.debug("timePeriod: {}", TIME_PERIOD); DEBUGGER.debug("URL_NAME: {}", URL_NAME); } try { // Set up mail session mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator()) : Session.getDefaultInstance(dataSource); if (DEBUG) { DEBUGGER.debug("mailSession: {}", mailSession); } if (mailSession == null) { throw new MessagingException("Unable to configure email services"); } mailSession.setDebug(DEBUG); Store mailStore = mailSession.getStore(URL_NAME); mailStore.connect(); if (DEBUG) { DEBUGGER.debug("mailStore: {}", mailStore); } if (!(mailStore.isConnected())) { throw new MessagingException("Failed to connect to mail service. Cannot continue."); } mailFolder = mailStore.getFolder("inbox"); archiveFolder = mailStore.getFolder("archive"); if (!(mailFolder.exists())) { throw new MessagingException("Requested folder does not exist. Cannot continue."); } mailFolder.open(Folder.READ_WRITE); if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) { throw new MessagingException("Failed to open requested folder. Cannot continue"); } if (!(archiveFolder.exists())) { archiveFolder.create(Folder.HOLDS_MESSAGES); } Message[] mailMessages = mailFolder.getMessages(); if (mailMessages.length == 0) { throw new MessagingException("No messages were found in the provided store."); } emailMessages = new ArrayList<EmailMessage>(); for (Message message : mailMessages) { if (DEBUG) { DEBUGGER.debug("MailMessage: {}", message); } // validate the message here String messageId = message.getHeader("Message-ID")[0]; Long messageDate = message.getReceivedDate().getTime(); if (DEBUG) { DEBUGGER.debug("messageId: {}", messageId); DEBUGGER.debug("messageDate: {}", messageDate); } // only get emails for the last 24 hours // this should prevent us from pulling too // many emails if (messageDate >= TIME_PERIOD) { // process it Multipart attachment = (Multipart) message.getContent(); Map<String, InputStream> attachmentList = new HashMap<String, InputStream>(); for (int x = 0; x < attachment.getCount(); x++) { BodyPart bodyPart = attachment.getBodyPart(x); if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) { continue; } attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream()); } List<String> toList = new ArrayList<String>(); List<String> ccList = new ArrayList<String>(); List<String> bccList = new ArrayList<String>(); List<String> fromList = new ArrayList<String>(); for (Address from : message.getFrom()) { fromList.add(from.toString()); } if ((message.getRecipients(RecipientType.TO) != null) && (message.getRecipients(RecipientType.TO).length != 0)) { for (Address to : message.getRecipients(RecipientType.TO)) { toList.add(to.toString()); } } if ((message.getRecipients(RecipientType.CC) != null) && (message.getRecipients(RecipientType.CC).length != 0)) { for (Address cc : message.getRecipients(RecipientType.CC)) { ccList.add(cc.toString()); } } if ((message.getRecipients(RecipientType.BCC) != null) && (message.getRecipients(RecipientType.BCC).length != 0)) { for (Address bcc : message.getRecipients(RecipientType.BCC)) { bccList.add(bcc.toString()); } } EmailMessage emailMessage = new EmailMessage(); emailMessage.setMessageTo(toList); emailMessage.setMessageCC(ccList); emailMessage.setMessageBCC(bccList); emailMessage.setEmailAddr(fromList); emailMessage.setMessageAttachments(attachmentList); emailMessage.setMessageDate(message.getSentDate()); emailMessage.setMessageSubject(message.getSubject()); emailMessage.setMessageBody(message.getContent().toString()); emailMessage.setMessageSources(message.getHeader("Received")); if (DEBUG) { DEBUGGER.debug("emailMessage: {}", emailMessage); } emailMessages.add(emailMessage); if (DEBUG) { DEBUGGER.debug("emailMessages: {}", emailMessages); } } // archive it archiveFolder.open(Folder.READ_WRITE); if (archiveFolder.isOpen()) { mailFolder.copyMessages(new Message[] { message }, archiveFolder); message.setFlag(Flags.Flag.DELETED, true); } } } catch (IOException iox) { throw new MessagingException(iox.getMessage(), iox); } catch (MessagingException mex) { throw new MessagingException(mex.getMessage(), mex); } finally { try { if ((mailFolder != null) && (mailFolder.isOpen())) { mailFolder.close(true); } if ((archiveFolder != null) && (archiveFolder.isOpen())) { archiveFolder.close(false); } } catch (MessagingException mx) { ERROR_RECORDER.error(mx.getMessage(), mx); } } return emailMessages; }
From source file:net.wastl.webmail.server.WebMailSession.java
public void removeFolder(String id, boolean recurse) throws MessagingException { Folder folder = getFolder(id); if (folder.isOpen()) folder.close(false);/*from w w w. j av a 2 s. c om*/ folder.delete(recurse); // Should be called from FolderSetup Plugin //refreshFolderInformation(); }
From source file:net.wastl.webmail.server.WebMailSession.java
/** Disconnect from mailhost "name"// w ww.j av a 2s. co m */ public void disconnect(String name) { try { Folder f = connections.get(name); if (f != null && f.isOpen()) { f.close(true); Store st = connections.get(name).getStore(); //st.close(); log.info("Mail: Disconnected from folder " + f.toString() + " at store " + st.toString() + "."); } else { log.warn("Mail: Folder " + name + " was null???."); } } catch (MessagingException ex) { // Should not happen log.fatal("Unexpected failure to disconnect", ex); } catch (NullPointerException ex) { // This happens when deleting a folder with an error log.fatal("Failed to disconnect after deleting folder? " + ex); // Log exception too if the comment above is wrong } finally { connections.remove(name); } }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Expunge all folders that have messages waiting to be deleted *//*w ww .j av a2 s . c o m*/ public void expungeFolders() { if (need_expunge_folders != null) { Enumeration<String> enumVar = need_expunge_folders.elements(); while (enumVar.hasMoreElements()) { String hash = (String) enumVar.nextElement(); if (user.wantsSetFlags()) { Folder f = getFolder(hash); try { if (f.isOpen()) { f.close(false); } f.open(Folder.READ_WRITE); // POP3 doesn't support expunge! try { f.expunge(); } catch (MessagingException ex) { } f.close(true); } catch (MessagingException ex) { // XXXX log.error("Failed to expunge folders", ex); } } } } }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Copy or move the selected messages from folder fromfolder to folder tofolder. *///from w w w . j ava2 s . c om public void copyMoveMessage(String fromfolder, String tofolder, HTTPRequestHeader head, boolean move) throws MessagingException { Folder from = getFolder(fromfolder); Folder to = getFolder(tofolder); if (user.wantsSetFlags()) { if (from.isOpen() && from.getMode() == Folder.READ_ONLY) { from.close(false); from.open(Folder.READ_WRITE); } else if (!from.isOpen()) { from.open(Folder.READ_WRITE); } if (to.isOpen() && to.getMode() == Folder.READ_ONLY) { to.close(false); to.open(Folder.READ_WRITE); } else if (!to.isOpen()) { to.open(Folder.READ_WRITE); } } else { if (!from.isOpen()) { from.open(Folder.READ_ONLY); } if (to.isOpen() && to.getMode() == Folder.READ_ONLY) { to.close(false); to.open(Folder.READ_WRITE); } else if (!to.isOpen()) { to.open(Folder.READ_WRITE); } } int m[] = getSelectedMessages(head, from.getMessageCount()); Message msgs[] = from.getMessages(m); from.copyMessages(msgs, to); if (move && user.wantsSetFlags()) { from.setFlags(m, new Flags(Flags.Flag.DELETED), true); if (user.getBoolVar("autoexpunge")) { from.close(true); to.close(true); } else { if (need_expunge_folders == null) { need_expunge_folders = new Vector<String>(); } need_expunge_folders.addElement(fromfolder); from.close(false); to.close(false); } } else { from.close(false); if (user.getBoolVar("autoexpunge")) { to.close(true); } else { to.close(false); } } from.open(Folder.READ_WRITE); to.open(Folder.READ_WRITE); refreshFolderInformation(fromfolder); refreshFolderInformation(tofolder); }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Fetch a message from a folder./*from w w w .jav a 2 s . c o m*/ * Will put the messages parameters in the sessions environment * * @param foldername Name of the folder were the message should be fetched from * @param msgnum Number of the message to fetch * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message * into the current work element of the user and set some additional flags on the message if the user * has enabled this option. * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD */ public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException { // security reasons: // attachments=null; try { TimeZone tz = TimeZone.getDefault(); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, user.getPreferredLocale()); df.setTimeZone(tz); Folder folder = getFolder(folderhash); Element xml_folder = model.getFolder(folderhash); if (folder == null) { throw new NoSuchFolderException("No such folder: " + folderhash); } if (folder.isOpen() && folder.getMode() == Folder.READ_WRITE) { folder.close(false); folder.open(Folder.READ_ONLY); } else if (!folder.isOpen()) { folder.open(Folder.READ_ONLY); } MimeMessage m = (MimeMessage) folder.getMessage(msgnum); String messageid; try { StringTokenizer tok = new StringTokenizer(m.getMessageID(), "<>"); messageid = tok.nextToken(); } catch (NullPointerException ex) { // For mail servers that don't generate a Message-ID (Outlook et al) messageid = user.getLogin() + "." + msgnum + ".jwebmail@" + user.getDomain(); } Element xml_current = model.setCurrentMessage(messageid); XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid); /* Check whether we already cached this message (not only headers but complete)*/ boolean cached = xml_message.messageCompletelyCached(); /* If we cached the message, we don't need to fetch it again */ if (!cached) { //Element xml_header=model.getHeader(xml_message); try { String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom())); String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo())); String to = MimeUtility .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO))); String cc = MimeUtility .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC))); String bcc = MimeUtility .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC))); Date date_orig = m.getSentDate(); String date = getStringResource("no date"); if (date_orig != null) { date = df.format(date_orig); } String subject = ""; if (m.getSubject() != null) { subject = MimeUtility.decodeText(m.getSubject()); } if (subject == null || subject.equals("")) { subject = getStringResource("no subject"); } try { Flags.Flag[] sf = m.getFlags().getSystemFlags(); 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"); } } catch (NullPointerException ex) { } if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) { xml_message.setAttribute("attachment", "true"); } int size = m.getSize(); size /= 1024; xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB"); /* Set all of what we found into the DOM */ xml_message.setHeader("FROM", from); xml_message.setHeader("SUBJECT", Fancyfier.apply(subject)); xml_message.setHeader("TO", to); xml_message.setHeader("CC", cc); xml_message.setHeader("BCC", bcc); xml_message.setHeader("REPLY-TO", replyto); xml_message.setHeader("DATE", date); /* Decode MIME contents recursively */ xml_message.removeAllParts(); parseMIMEContent(m, xml_message, messageid); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage()); } } /* Set seen flag (Maybe make that threaded to improve performance) */ if (user.wantsSetFlags()) { if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) { folder.close(false); folder.open(Folder.READ_WRITE); } else if (!folder.isOpen()) { folder.open(Folder.READ_WRITE); } folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true); folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false); if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) { folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true); } } folder.close(false); /* In this part we determine whether the message was requested so that it may be used for further editing (replying or forwarding). In this case we set the current "work" message to the message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */ XMLMessage work = null; if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) { log.debug("Setting work message!"); work = model.setWorkMessage(xml_message); String newmsgid = WebMailServer.generateMessageID(user.getUserName()); if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) { String from = work.getHeader("FROM"); work.setHeader("FROM", user.getDefaultEmail()); work.setHeader("TO", from); work.prepareReply(getStringResource("reply subject prefix"), getStringResource("reply subject postfix"), getStringResource("reply message prefix"), getStringResource("reply message postfix")); } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) { String from = work.getHeader("FROM"); work.setHeader("FROM", user.getDefaultEmail()); work.setHeader("TO", ""); work.setHeader("CC", ""); work.prepareForward(getStringResource("forward subject prefix"), getStringResource("forward subject postfix"), getStringResource("forward message prefix"), getStringResource("forward message postfix")); /* Copy all references to MIME parts to the new message id */ for (String key : getMimeParts(work.getAttribute("msgid"))) { StringTokenizer tok2 = new StringTokenizer(key, "/"); tok2.nextToken(); String newkey = tok2.nextToken(); mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key)); } } /* Clear the msgnr and msgid fields at last */ work.setAttribute("msgnr", "0"); work.setAttribute("msgid", newmsgid); prepareCompose(); } } catch (MessagingException ex) { log.error("Failed to get message. Doing nothing instead.", ex); } }
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 {/*from w ww . j a va 2 s. c om*/ 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()); } } }
From source file:org.zilverline.core.IMAPCollection.java
private final boolean indexFolder(IndexWriter writer, Folder thisFolder) throws MessagingException { if (stopRequested) { log.info("Indexing stops, due to request"); return false; }/*from w w w .j ava 2s . com*/ if ((thisFolder.getType() & Folder.HOLDS_MESSAGES) != 0) { thisFolder.open(Folder.READ_ONLY); Message[] messages = thisFolder.getMessages(); // get refs to all msgs if (messages == null) { // dummy messages = new Message[0]; } thisFolder.fetch(messages, PROFILE); // fetch headers log.debug("FOLDER: " + thisFolder.getFullName() + " messages=" + messages.length); for (int i = 0; i < messages.length; i++) { try { String msgID = null; if (messages[i] instanceof MimeMessage) { MimeMessage mm = (MimeMessage) messages[i]; msgID = mm.getMessageID(); } if (!md5DocumentCache.contains(msgID)) { log.debug("new message added for message: " + msgID); final Document doc = new Document(); doc.add(Field.Keyword(F_FOLDER, thisFolder.getFullName())); doc.add(Field.Keyword("collection", name)); // index this message indexMessage(doc, messages[i]); // add it writer.addDocument(doc); md5DocumentCache.add(msgID); } else { log.debug("existing message skipped for message: " + msgID); } } catch (Exception ioe) { // can be side effect of hosed up mail headers log.warn("Bad Message: " + messages[i], ioe); continue; } } } // recurse if possible if ((thisFolder.getType() & Folder.HOLDS_FOLDERS) != 0) { Folder[] far = thisFolder.list(); if (far != null) { for (int i = 0; i < far.length; i++) { indexFolder(writer, far[i]); } } } if (thisFolder.isOpen()) { log.debug("Closing folder: " + thisFolder.getFullName()); thisFolder.close(false); // false => do not expunge } return true; }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Create a Message List./*ww w . j ava 2 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
/** Change the Flags of the messages the user selected. //from w w w .j a v a 2s. c o m */ public void setFlags(String folderhash, HTTPRequestHeader head) throws MessagingException { if (head.isContentSet("copymovemsgs") && head.getContent("COPYMOVE").equals("COPY")) { copyMoveMessage(folderhash, head.getContent("TO"), head, false); } else if (head.isContentSet("copymovemsgs") && head.getContent("COPYMOVE").equals("MOVE")) { copyMoveMessage(folderhash, head.getContent("TO"), head, true); } else if (head.isContentSet("flagmsgs")) { log.debug("setting message flags"); Folder folder = getFolder(folderhash); //log.debug("Processing Request Header..."); /* Get selected messages */ int msgs[] = getSelectedMessages(head, folder.getMessageCount()); //log.debug("get flags..."); /* Get selected flags */ Flags fl = new Flags(Flags.Flag.USER); if (head.getContent("MESSAGE FLAG").equals("DELETED")) { fl = new Flags(Flags.Flag.DELETED); if (need_expunge_folders == null) { need_expunge_folders = new Vector<String>(); } need_expunge_folders.addElement(folderhash); } else if (head.getContent("MESSAGE FLAG").equals("SEEN")) { fl = new Flags(Flags.Flag.SEEN); } else if (head.getContent("MESSAGE FLAG").equals("RECENT")) { fl = new Flags(Flags.Flag.RECENT); } else if (head.getContent("MESSAGE FLAG").equals("ANSWERED")) { fl = new Flags(Flags.Flag.ANSWERED); } else if (head.getContent("MESSAGE FLAG").equals("DRAFT")) { fl = new Flags(Flags.Flag.DRAFT); } boolean value = true; if (head.getContent("MARK").equals("UNMARK")) { value = false; } //log.debug("Done!"); //log.debug("Setting flags..."); if (user.wantsSetFlags()) { if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) { folder.close(false); folder.open(Folder.READ_WRITE); } else if (!folder.isOpen()) { folder.open(Folder.READ_WRITE); } folder.setFlags(msgs, fl, value); if (user.getBoolVar("autoexpunge")) { folder.close(true); if (need_expunge_folders != null) { need_expunge_folders.removeElement(folderhash); } } else { folder.close(false); } } folder.open(Folder.READ_WRITE); refreshFolderInformation(folderhash); } }