List of usage examples for javax.mail.internet MimeUtility javaCharset
public static String javaCharset(String charset)
From source file:com.zotoh.crypto.CryptoUte.java
/** * @param cType/*from www.j a v a2s. c om*/ * @param deFcs * @return */ public static String getCharset(String cType, String deFcs) { String cs = getCharset(cType); return isEmpty(cs) ? MimeUtility.javaCharset(deFcs) : cs; }
From source file:com.zotoh.crypto.CryptoUte.java
/** * @param cType//from ww w . j a v a2 s. c o m * @return */ public static String getCharset(String cType) { String rc = null; if (!isEmpty(cType)) try { String charset = (new ContentType(cType)).getParameter("charset"); rc = MimeUtility.javaCharset(charset); } catch (Exception e) { tlog().warn("", e); } return rc; }
From source file:com.duroty.application.open.manager.OpenManager.java
/** * DOCUMENT ME!/* w ww . ja va 2 s . c o m*/ * * @param msession DOCUMENT ME! * @param from DOCUMENT ME! * @param to DOCUMENT ME! * @param username DOCUMENT ME! * @param password DOCUMENT ME! * @param signature DOCUMENT ME! * * @throws Exception DOCUMENT ME! */ private void notifyToAdmins(Session msession, InternetAddress from, InternetAddress[] to, String user) throws Exception { try { HtmlEmail email = new HtmlEmail(); email.setMailSession(msession); email.setFrom(from.getAddress(), from.getPersonal()); HashSet aux = new HashSet(to.length); Collections.addAll(aux, to); email.setTo(aux); email.setSubject("User register in Duroty System"); email.setHtmlMsg( "<p>The user solicits register into the system</p><p>The user is: <b>" + user + "</b></p>"); email.setCharset(MimeUtility.javaCharset(Charset.defaultCharset().displayName())); email.send(); } finally { } }
From source file:com.duroty.application.mail.manager.SendManager.java
/** * DOCUMENT ME!/* w w w. j a v a 2 s .com*/ * * @param hsession DOCUMENT ME! * @param session DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param ideIdint DOCUMENT ME! * @param to DOCUMENT ME! * @param cc DOCUMENT ME! * @param bcc DOCUMENT ME! * @param subject DOCUMENT ME! * @param body DOCUMENT ME! * @param attachments DOCUMENT ME! * @param isHtml DOCUMENT ME! * @param charset DOCUMENT ME! * @param headers DOCUMENT ME! * @param priority DOCUMENT ME! * * @throws MailException DOCUMENT ME! */ public void saveDraft(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint, String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml, String charset, InternetHeaders headers, String priority) throws MailException { try { if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } if ((body == null) || body.trim().equals("")) { body = " "; } Email email = null; if (isHtml) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charset); Users user = getUser(hsession, repositoryName); Identity identity = getIdentity(hsession, ideIdint, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null); InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null); InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if ((_to != null) && (_to.length > 0)) { HashSet aux = new HashSet(_to.length); Collections.addAll(aux, _to); email.setTo(aux); } if ((_cc != null) && (_cc.length > 0)) { HashSet aux = new HashSet(_cc.length); Collections.addAll(aux, _cc); email.setCc(aux); } if ((_bcc != null) && (_bcc.length > 0)) { HashSet aux = new HashSet(_bcc.length); Collections.addAll(aux, _bcc); email.setBcc(aux); } email.setSubject(subject); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } if ((attachments != null) && (attachments.size() > 0)) { for (int i = 0; i < attachments.size(); i++) { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { MailPartObj obj = (MailPartObj) attachments.get(i); File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); if (email instanceof MultiPartEmail) { ((MultiPartEmail) email).attach(attachment); } } catch (Exception ex) { } finally { IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } } } if (headers != null) { Header xheader; Enumeration xe = headers.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) { email.addHeader(xheader.getName(), xheader.getValue()); } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) { email.addHeader(xheader.getName(), xheader.getValue()); } } } if (priority != null) { if (priority.equals("high")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "1"); } else if (priority.equals("low")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "5"); } } if (email instanceof HtmlEmail) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeDraftMessage(getId(), mime, user); } catch (MailException e) { throw e; } catch (Exception e) { throw new MailException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new MailException(ex); } catch (Throwable e) { throw new MailException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!// w ww. j av a2 s . c o m * * @param dmailParts DOCUMENT ME! * @param contentType DOCUMENT ME! * @param buffer DOCUMENT ME! * * @return DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ protected static StringBuffer scanDmailParts(Vector dmailParts, StringBuffer buffer, boolean chooseHtml, String breakLine) throws MessagingException { if ((buffer.length() == 0) && (dmailParts != null)) { int size = dmailParts.size(); int j = 0; for (int i = 0; i < size; i++) { //message/rfc822 MailPart dmailPart = (MailPart) dmailParts.get(j); //ContentType xctype = MessageUtilities.getContentType(dmailPart.getContentType()); ContentType xctype = MessageUtilities.getContentType(dmailPart.getPart()); if (xctype.match("text/plain") && !chooseHtml) { String xjcharset = xctype.getParameter("charset"); if (xjcharset == null) { // not present, assume ASCII character encoding try { Header xheader; Enumeration xe = dmailPart.getPart().getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); String aux = xheader.getName().toLowerCase().trim(); if (aux.indexOf("subject") > -1) { int pos1 = aux.indexOf("=?"); int pos2 = aux.indexOf("?q?"); if ((pos1 > -1) && (pos2 > -1)) { xjcharset = aux.substring(pos1, pos2); } break; } } } catch (Exception ex) { } if (xjcharset == null) { xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms } } //String str = JavaScriptFilter.apply(buff.toString()); xjcharset = MimeUtility.javaCharset(xjcharset); MessageUtilities.decodeTextPlain(buffer, dmailPart.getPart(), breakLine, xjcharset); dmailParts.removeElementAt(j); break; } else if (xctype.match("text/html") && chooseHtml) { String xjcharset = xctype.getParameter("charset"); if (xjcharset == null) { // not present, assume ASCII character encoding try { Header xheader; Enumeration xe = dmailPart.getPart().getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); String aux = xheader.getName().toLowerCase().trim(); if (aux.indexOf("subject") > -1) { int pos1 = aux.indexOf("=?"); int pos2 = aux.indexOf("?q?"); if ((pos1 > -1) && (pos2 > -1)) { xjcharset = aux.substring(pos1, pos2); } break; } } } catch (Exception ex) { } if (xjcharset == null) { xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms } } xjcharset = MimeUtility.javaCharset(xjcharset); MessageUtilities.decodeTextHtml(buffer, dmailPart.getPart(), xjcharset); dmailParts.removeElementAt(j); break; } else { j++; } } } return buffer; }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//from www . ja va 2s . c o m * * @param buffer DOCUMENT ME! * @param part DOCUMENT ME! * * @return DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static StringBuffer decodeTextHtml(StringBuffer buffer, Part part, String charset) { BufferedReader xreader = null; ByteArrayInputStream bais = null; ByteArrayOutputStream baos = null; try { charset = MimeUtility.javaCharset(charset); xreader = MessageUtilities.getTextReader(part, charset); String body = IOUtils.toString(xreader); //buffer.append(JavaScriptFilter.apply(body)); buffer.append(body); return buffer; } catch (Exception xex) { buffer = new StringBuffer(); return buffer; } finally { IOUtils.closeQuietly(xreader); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(baos); } }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//w w w . ja v a2s. c o m * * @param buffer DOCUMENT ME! * @param bytes DOCUMENT ME! * @param charset DOCUMENT ME! * * @return DOCUMENT ME! */ public static StringBuffer decodeTextHtml(StringBuffer buffer, byte[] bytes, String charset) { ByteArrayInputStream bais = null; ByteArrayOutputStream baos = null; try { String body = new String(bytes); charset = MimeUtility.javaCharset(charset); //buffer.append(JavaScriptFilter.apply(body)); buffer.append(body); return buffer; } catch (Exception xex) { buffer = new StringBuffer(); return buffer; } finally { IOUtils.closeQuietly(bais); IOUtils.closeQuietly(baos); } }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!/*from ww w. j a v a2s. c om*/ * * @param stream DOCUMENT ME! * @param charset DOCUMENT ME! * * @return DOCUMENT ME! * * @throws UnsupportedEncodingException DOCUMENT ME! */ public static BufferedReader getTextReader(InputStream stream, String charset) throws UnsupportedEncodingException { // Sun has a HUGE bug in their io code. They use a cute coding trick // that appends the charset to a prefix to create a Class name that // they then attempt to load. The problem is that if the charset is // not one that they "recognize", and the name has something like a // dash character in it, the resulting Class name has an invalid // character in it. This results in an IllegalArgumentException // instead of the UnsupportedEncodingException that we expect. Thus, // we need to catch the undocumented exception. InputStreamReader inReader; try { charset = MimeUtility.javaCharset(charset); // just to be sure inReader = new InputStreamReader(stream, charset); } catch (UnsupportedEncodingException ex) { inReader = null; } catch (IllegalArgumentException ex) { inReader = null; } if (inReader == null) { // This is the "bug" case, and we need to do something // that will at least put text in front of the user... inReader = new InputStreamReader(stream, Charset.defaultCharset().displayName()); } return new BufferedReader(inReader); }
From source file:net.wastl.webmail.server.WebMailSession.java
/** Use depth-first search to go through MIME-Parts recursively. @param p Part to begin with//w ww . j a va2s. c o m */ protected void parseMIMEContent(Part p, XMLMessagePart parent_part, String msgid) throws MessagingException { StringBuilder content = new StringBuilder(1000); XMLMessagePart xml_part; try { if (p.getContentType().toUpperCase().startsWith("TEXT/HTML")) { /* The part is a text in HTML format. We will try to use "Tidy" to create a well-formatted XHTML DOM from it and then remove JavaScript and other "evil" stuff. For replying to such a message, it will be useful to just remove all of the tags and display only the text. */ xml_part = parent_part.createPart("html"); /**************************************************** * LEAVING THESE OLD XML PARSERS COMMENTED OUT * until know that the new Parser tactic parses HTML properly * (or adequately). See the ** comment below. /* Here we create a DOM tree. //Tidy tidy=new Tidy(); //tidy.setUpperCaseTags(true); //Document htmldoc=tidy.parseDOM(p.getInputStream(),null); // org.cyberneko.html.parsers.DOMParser parser = // new org.cyberneko.html.parsers.DOMParser(); // DOMParser parser = new DOMParser(new HTMLConfiguration()); // parser.parse(new InputSource(p.getInputStream())); // Document htmldoc = parser.getDocument(); // instantiate a DOM implementation DOM dom = new com.docuverse.dom.DOM(); // install the SAX driver for Swing HTML parser dom.setProperty("sax.driver", "com.docuverse.html.swing.SAXDriver"); // install HTML element factory dom.setFactory(new com.docuverse.dom.html.HTMLFactory()); // ** N.B. WITH docuverse AND NekoHTML, THE PARSER WAS // HTML-Specific. We are now using generic XML parser. // Is that adequate? // now just open the document Document htmldoc = (Document)dom.readDocument(p.getInputStream()); */ javax.xml.parsers.DocumentBuilder parser = javax.xml.parsers.DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document htmldoc = parser.parse(p.getInputStream()); if (htmldoc == null) { log.error("Document was null!"); // Why not throwing? } //dom.writeDocument(htmldoc,"/tmp/test.xml"); /* Now let's look for all the malicious JavaScript and other <SCRIPT> tags, URLS containing the "javascript:" and tags containing "onMouseOver" and such stuff. */ // if(user.getBoolVar("filter javascript")) new JavaScriptCleaner(htmldoc); new JavaScriptCleaner(htmldoc); //dom.writeDocument(htmldoc,"/tmp/test2.xml"); //XMLCommon.debugXML(htmldoc); /* HTML doesn't allow us to do such fancy stuff like different quote colors, perhaps this will be implemented in the future */ /* So we just add this HTML document to the message part, which will deal with removing headers and tags that we don't need */ xml_part.addContent(htmldoc); } else if (p.getContentType().toUpperCase().startsWith("TEXT") || p.getContentType().toUpperCase().startsWith("MESSAGE")) { /* The part is a standard message part in some incarnation of text (html or plain). We should decode it and take care of some extra issues like recognize quoted parts, filter JavaScript parts and replace smileys with smiley-icons if the user has set wantsFancy() */ xml_part = parent_part.createPart("text"); // TODO: log.debug("text hit"); BufferedReader in; if (p instanceof MimeBodyPart) { int size = p.getSize(); MimeBodyPart mpb = (MimeBodyPart) p; InputStream is = mpb.getInputStream(); /* Workaround for Java or Javamail Bug */ is = new BufferedInputStream(is); ByteStore ba = ByteStore.getBinaryFromIS(is, size); in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(ba.getBytes()))); /* End of workaround */ size = is.available(); } else { in = new BufferedReader(new InputStreamReader(p.getInputStream())); } log.debug("Content-Type: " + p.getContentType()); String token = ""; int quote_level = 0, old_quotelevel = 0; boolean javascript_mode = false; /* Read in the message part line by line */ while ((token = in.readLine()) != null) { /* First decode all language and MIME dependant stuff */ // Default to ISO-8859-1 (Western Latin 1) String charset = "ISO-8859-1"; // Check whether the part contained a charset in the content-type header StringTokenizer tok2 = new StringTokenizer(p.getContentType(), ";="); String blah = tok2.nextToken(); if (tok2.hasMoreTokens()) { blah = tok2.nextToken().trim(); if (blah.toLowerCase().equals("charset") && tok2.hasMoreTokens()) { charset = tok2.nextToken().trim(); } } try { token = new String(token.getBytes(), charset); } catch (UnsupportedEncodingException ex1) { log.info("Java Engine does not support charset " + charset + ". Trying to convert from MIME ..."); try { charset = MimeUtility.javaCharset(charset); token = new String(token.getBytes(), charset); } catch (UnsupportedEncodingException ex) { log.warn("Converted charset (" + charset + ") does not work. Using default charset (ouput may contain errors)"); token = new String(token.getBytes()); } } /* Here we figure out which quote level this line has, simply by counting how many ">" are in front of the line, ignoring all whitespaces. */ int current_quotelevel = Helper.getQuoteLevel(token); /* When we are in a different quote level than the last line, we append all we got so far to the part with the old quotelevel and begin with a clean String buffer */ if (current_quotelevel != old_quotelevel) { xml_part.addContent(content.toString(), old_quotelevel); old_quotelevel = current_quotelevel; content = new StringBuilder(1000); } if (user.wantsBreakLines()) { Enumeration enumVar = Helper.breakLine(token, user.getMaxLineLength(), current_quotelevel); while (enumVar.hasMoreElements()) { String s = (String) enumVar.nextElement(); if (user.wantsShowFancy()) { content.append(Fancyfier.apply(s)).append("\n"); } else { content.append(s).append("\n"); } } } else { if (user.wantsShowFancy()) { content.append(Fancyfier.apply(token)).append("\n"); } else { content.append(token).append("\n"); } } } xml_part.addContent(content.toString(), old_quotelevel); // Why the following code??? content = new StringBuilder(1000); } else if (p.getContentType().toUpperCase().startsWith("MULTIPART/ALTERNATIVE")) { /* This is a multipart/alternative part. That means that we should pick one of the formats and display it for this part. Our current precedence list is to choose HTML first and then to choose plain text. */ MimeMultipart m = (MimeMultipart) p.getContent(); String[] preferred = { "TEXT/HTML", "TEXT" }; boolean found = false; int alt = 0; // Walk though our preferred list of encodings. If we have found a fitting part, // decode it and replace it for the parent (this is what we really want with an // alternative!) /** findalt: while(!found && alt < preferred.length) { for(int i=0;i<m.getCount();i++) { Part p2=m.getBodyPart(i); if(p2.getContentType().toUpperCase().startsWith(preferred[alt])) { parseMIMEContent(p2,parent_part,msgid); found=true; break findalt; } } alt++; } **/ /** * When user try to reply a mail, there may be 3 conditions: * 1. only TEXT exists. * 2. both HTML and TEXT exist. * 3. only HTML exists. * * We have to choose which part should we quote, that is, we must * decide the prority of parts to quote. Since quoting HTML is not * easy and precise (consider a html: <body><div><b>some text..</b> * </div></body>. Even we try to get text node under <body>, we'll * just get nothing, because "some text..." is marked up by * <div><b>. There is no easy way to retrieve text from html * unless we parse the html to analyse its semantics. * * Here is our policy for alternative part: * 1. Displays HTML but hides TEXT. * 2. When replying this mail, try to quote TEXT part. If no TEXT * part exists, quote HTML in best effort(use * XMLMessagePart.quoteContent() by Sebastian Schaffert.) */ while (alt < preferred.length) { for (int i = 0; i < m.getCount(); i++) { Part p2 = m.getBodyPart(i); if (p2.getContentType().toUpperCase().startsWith(preferred[alt])) { log.debug("Processing: " + p2.getContentType()); parseMIMEContent(p2, parent_part, msgid); found = true; break; } } /** * If we've selected HTML part from alternative part, the TEXT * part should be hidden from display but keeping in XML for * later quoting operation. * * Of course, this requires some modification on showmessage.xsl. */ if (found && (alt == 1)) { Node textPartNode = parent_part.getPartElement().getLastChild(); NamedNodeMap attributes = textPartNode.getAttributes(); boolean hit = false; for (int i = 0; i < attributes.getLength(); ++i) { Node attr = attributes.item(i); // If type=="TEXT", add a hidden attribute. if (attr.getNodeName().toUpperCase().equals("TYPE") && attr.getNodeValue().toUpperCase().equals("TEXT")) { ((Element) textPartNode).setAttribute("hidden", "true"); } } } alt++; } if (!found) { // If we didn't find one of our preferred encodings, choose the first one // simply pass the parent part because replacement is what we really want with // an alternative. parseMIMEContent(m.getBodyPart(0), parent_part, msgid); } } else if (p.getContentType().toUpperCase().startsWith("MULTIPART/")) { /* This is a standard multipart message. We should recursively walk thorugh all of the parts and decode them, appending as children to the current part */ xml_part = parent_part.createPart("multi"); MimeMultipart m = (MimeMultipart) p.getContent(); for (int i = 0; i < m.getCount(); i++) { parseMIMEContent(m.getBodyPart(i), xml_part, msgid); } } else { /* Else treat the part as a binary part that the user should either download or get displayed immediately in case of an image */ InputStream in = null; String type = ""; if (p.getContentType().toUpperCase().startsWith("IMAGE/JPG") || p.getContentType().toUpperCase().startsWith("IMAGE/JPEG")) { type = "jpg"; xml_part = parent_part.createPart("image"); } else if (p.getContentType().toUpperCase().startsWith("IMAGE/GIF")) { type = "gif"; xml_part = parent_part.createPart("image"); } else if (p.getContentType().toUpperCase().startsWith("IMAGE/PNG")) { type = "png"; xml_part = parent_part.createPart("image"); } else { xml_part = parent_part.createPart("binary"); } int size = p.getSize(); if (p instanceof MimeBodyPart) { MimeBodyPart mpb = (MimeBodyPart) p; log.debug("MIME Body part (image), Encoding: " + mpb.getEncoding()); InputStream is = mpb.getInputStream(); /* Workaround for Java or Javamail Bug */ in = new BufferedInputStream(is); ByteStore ba = ByteStore.getBinaryFromIS(in, size); in = new ByteArrayInputStream(ba.getBytes()); /* End of workaround */ size = in.available(); } else { log.warn("No MIME Body part!!"); // Is this unexpected? Consider changing log level. in = p.getInputStream(); } ByteStore data = ByteStore.getBinaryFromIS(in, size); if (mime_parts_decoded == null) { mime_parts_decoded = new HashMap<String, ByteStore>(); } String name = p.getFileName(); if (name == null || name.equals("")) { // Try an other way String headers[] = p.getHeader("Content-Disposition"); int pos = -1; if (headers.length == 1) { pos = headers[0].indexOf("filename*=") + 10; } if (pos != -1) { int charsetEnds = headers[0].indexOf("''", pos); String charset = headers[0].substring(pos, charsetEnds); String encodedFileName = headers[0].substring(charsetEnds + 2); encodedFileName = "=?" + charset + "?Q?" + encodedFileName.replace('%', '=') + "?="; name = MimeUtility.decodeText(encodedFileName); } else { name = "unknown." + type; } } // Eliminate space characters. Should do some more things in the future name = name.replace(' ', '_'); data.setContentType(p.getContentType()); data.setContentEncoding("BINARY"); mime_parts_decoded.put(msgid + "/" + name, data); /** * For multibytes language system, we have to separate filename into * 2 format: one for display (UTF-8 encoded), another for encode the * url of hyperlink. * `filename' is for display, while `hrefFileName' is for hyperlink. * To make use of these two attributes, `showmessage.xsl' is slightly * modified. */ data.setName(name); xml_part.setAttribute("filename", name); // Transcode name into UTF-8 bytes then make a new ISO8859_1 string to encode URL. xml_part.setAttribute("hrefFileName", name); xml_part.setAttribute("size", size + ""); String description = p.getDescription() == null ? "" : p.getDescription(); xml_part.setAttribute("description", description); StringTokenizer tok = new StringTokenizer(p.getContentType(), ";"); xml_part.setAttribute("content-type", tok.nextToken().toLowerCase()); } } catch (java.io.IOException ex) { log.error("Failed to parse mime content", ex); } catch (MessagingException ex) { log.error("Failed to parse mime content", ex); } catch (Exception ex) { log.error("Failed to parse mime content", ex); } }
From source file:org.sakaiproject.james.SakaiMailet.java
/** * Breaks email messages into parts which can be saved as files (saves as attachments) or viewed as plain text (added to body of message). * /*from ww w . j av a 2 s .c o m*/ * @param siteId * Site associated with attachments, if any * @param p * The message-part embedded in a message.. * @param id * The string containing the message's id. * @param bodyBuf * The string-buffers in which the plain/text and/or html/text message body is being built. * @param bodyContentType * The value of the Content-Type header for the mesage body. * @param attachments * The ReferenceVector in which references to attachments are collected. * @param embedCount * An Integer that counts embedded messages (outer message is zero). * @return Value of embedCount (updated if this call processed any embedded messages). */ protected Integer parseParts(String siteId, Part p, String id, StringBuilder bodyBuf[], StringBuilder bodyContentType, List attachments, Integer embedCount) throws MessagingException, IOException { // increment embedded message counter if (p instanceof Message) { embedCount = Integer.valueOf(embedCount.intValue() + 1); } String type = p.getContentType(); // discard if content-type is unknown if (type == null || "".equals(type)) { M_log.warn(this + " message with unknown content-type discarded"); } // add plain text to bodyBuf[0] else if (p.isMimeType("text/plain") && p.getFileName() == null) { Object o = null; // let them convert to text if possible // but if bad encaps get the stream and do it ourselves try { o = p.getContent(); } catch (java.io.UnsupportedEncodingException ignore) { o = p.getInputStream(); } String txt = null; String innerContentType = p.getContentType(); if (o instanceof String) { txt = (String) p.getContent(); if (bodyContentType != null && bodyContentType.length() == 0) bodyContentType.append(innerContentType); } else if (o instanceof InputStream) { InputStream in = (InputStream) o; ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[in.available()]; for (int len = in.read(buf); len != -1; len = in.read(buf)) out.write(buf, 0, len); String charset = (new ContentType(innerContentType)).getParameter("charset"); // RFC 2045 says if no char set specified use US-ASCII. // If specified but illegal that's less clear. The common case is X-UNKNOWN. // my sense is that UTF-8 is most likely these days but the sample we got // was actually ISO 8859-1. Could also justify using US-ASCII. Duh... if (charset == null) charset = "us-ascii"; try { txt = out.toString(MimeUtility.javaCharset(charset)); } catch (java.io.UnsupportedEncodingException ignore) { txt = out.toString("UTF-8"); } if (bodyContentType != null && bodyContentType.length() == 0) bodyContentType.append(innerContentType); } // remove extra line breaks added by mac Mail, perhaps others // characterized by a space followed by a line break if (txt != null) { txt = txt.replaceAll(" \n", " "); } // make sure previous message parts ended with newline if (bodyBuf[0].length() > 0 && bodyBuf[0].charAt(bodyBuf[0].length() - 1) != '\n') bodyBuf[0].append("\n"); bodyBuf[0].append(txt); } // add html text to bodyBuf[1] else if (p.isMimeType("text/html") && p.getFileName() == null) { Object o = null; // let them convert to text if possible // but if bad encaps get the stream and do it ourselves try { o = p.getContent(); } catch (java.io.UnsupportedEncodingException ignore) { o = p.getInputStream(); } String txt = null; String innerContentType = p.getContentType(); if (o instanceof String) { txt = (String) p.getContent(); if (bodyContentType != null && bodyContentType.length() == 0) bodyContentType.append(innerContentType); } else if (o instanceof InputStream) { InputStream in = (InputStream) o; ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[in.available()]; for (int len = in.read(buf); len != -1; len = in.read(buf)) out.write(buf, 0, len); String charset = (new ContentType(innerContentType)).getParameter("charset"); if (charset == null) charset = "us-ascii"; try { txt = out.toString(MimeUtility.javaCharset(charset)); } catch (java.io.UnsupportedEncodingException ignore) { txt = out.toString("UTF-8"); } if (bodyContentType != null && bodyContentType.length() == 0) bodyContentType.append(innerContentType); } // remove bad image tags and naughty javascript if (txt != null) { txt = Web.cleanHtml(txt); } bodyBuf[1].append(txt); } // process subparts of multiparts else if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) { embedCount = parseParts(siteId, mp.getBodyPart(i), id, bodyBuf, bodyContentType, attachments, embedCount); } } // Discard parts with mime-type application/applefile. If an e-mail message contains an attachment is sent from // a macintosh, you may get two parts, one for the data fork and one for the resource fork. The part that // corresponds to the resource fork confuses users, this has mime-type application/applefile. The best thing // is to discard it. else if (p.isMimeType("application/applefile")) { M_log.warn(this + " message with application/applefile discarded"); } // discard enriched text version of the message. // Sakai only uses the plain/text or html/text version of the message. else if (p.isMimeType("text/enriched") && p.getFileName() == null) { M_log.warn(this + " message with text/enriched discarded"); } // everything else gets treated as an attachment else { String name = p.getFileName(); // look for filenames not parsed by getFileName() if (name == null && type.indexOf(NAME_PREFIX) != -1) { name = type.substring(type.indexOf(NAME_PREFIX) + NAME_PREFIX.length()); } // ContentType can't handle filenames with spaces or UTF8 characters if (name != null) { String decodedName = MimeUtility.decodeText(name); // first decode RFC 2047 type = type.replace(name, URLEncoder.encode(decodedName, "UTF-8")); name = decodedName; } ContentType cType = new ContentType(type); String disposition = p.getDisposition(); int approxSize = p.getSize(); if (name == null) { name = "unknown"; // if file's parent is multipart/alternative, // provide a better name for the file if (p instanceof BodyPart) { Multipart parent = ((BodyPart) p).getParent(); if (parent != null) { String pType = parent.getContentType(); ContentType pcType = new ContentType(pType); if (pcType.getBaseType().equalsIgnoreCase("multipart/alternative")) { name = "message" + embedCount; } } } if (p.isMimeType("text/html")) { name += ".html"; } else if (p.isMimeType("text/richtext")) { name += ".rtx"; } else if (p.isMimeType("text/rtf")) { name += ".rtf"; } else if (p.isMimeType("text/enriched")) { name += ".etf"; } else if (p.isMimeType("text/plain")) { name += ".txt"; } else if (p.isMimeType("text/xml")) { name += ".xml"; } else if (p.isMimeType("message/rfc822")) { name += ".txt"; } } // read the attachments bytes, and create it as an attachment in content hosting byte[] bodyBytes = readBody(approxSize, p.getInputStream()); if ((bodyBytes != null) && (bodyBytes.length > 0)) { // can we ignore the attachment it it's just whitespace chars?? Reference attachment = createAttachment(siteId, attachments, cType.getBaseType(), name, bodyBytes, id); // add plain/text attachment reference (if plain/text message) if (attachment != null && bodyBuf[0].length() > 0) bodyBuf[0] .append("[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]\n\n"); // add html/text attachment reference (if html/text message) if (attachment != null && bodyBuf[1].length() > 0) bodyBuf[1].append( "<p>[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]</p>"); // add plain/text attachment reference (if no plain/text and no html/text) if (attachment != null && bodyBuf[0].length() == 0 && bodyBuf[1].length() == 0) bodyBuf[0] .append("[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]\n\n"); } } return embedCount; }