List of usage examples for javax.mail Multipart getContentType
public synchronized String getContentType()
From source file:org.apache.hupa.server.handler.GetMessageDetailsHandler.java
/** * Handle the parts of the given message. The method will call itself recursively to handle all nested parts * @param message the MimeMessage //ww w . ja v a 2 s . c om * @param con the current processing Content * @param sbPlain the StringBuffer to fill with text * @param attachmentList ArrayList with attachments * @throws UnsupportedEncodingException * @throws MessagingException * @throws IOException */ protected boolean handleParts(MimeMessage message, Object con, StringBuffer sbPlain, ArrayList<MessageAttachment> attachmentList) throws UnsupportedEncodingException, MessagingException, IOException { boolean isHTML = false; if (con instanceof String) { if (message.getContentType().toLowerCase().startsWith("text/html")) { isHTML = true; } else { isHTML = false; } sbPlain.append((String) con); } else if (con instanceof Multipart) { Multipart mp = (Multipart) con; String multipartContentType = mp.getContentType().toLowerCase(); String text = null; if (multipartContentType.startsWith("multipart/alternative")) { isHTML = handleMultiPartAlternative(mp, sbPlain); } else { for (int i = 0; i < mp.getCount(); i++) { Part part = mp.getBodyPart(i); String contentType = part.getContentType().toLowerCase(); Boolean bodyRead = sbPlain.length() > 0; if (!bodyRead && contentType.startsWith("text/plain")) { isHTML = false; text = (String) part.getContent(); } else if (!bodyRead && contentType.startsWith("text/html")) { isHTML = true; text = (String) part.getContent(); } else if (!bodyRead && contentType.startsWith("message/rfc822")) { // Extract the message and pass it MimeMessage msg = (MimeMessage) part.getDataHandler().getContent(); isHTML = handleParts(msg, msg.getContent(), sbPlain, attachmentList); } else { if (part.getFileName() != null) { // Inline images are not added to the attachment list // TODO: improve the in-line images detection if (part.getHeader("Content-ID") == null) { MessageAttachment attachment = new MessageAttachment(); attachment.setName(MimeUtility.decodeText(part.getFileName())); attachment.setContentType(part.getContentType()); attachment.setSize(part.getSize()); attachmentList.add(attachment); } } else { isHTML = handleParts(message, part.getContent(), sbPlain, attachmentList); } } } if (text != null) sbPlain.append(text); } } return isHTML; }
From source file:org.apache.hupa.server.utils.MessageUtils.java
/** * Handle the parts of the given message. The method will call itself * recursively to handle all nested parts * * @param message the MimeMessage/*from w ww. j a v a 2 s . c om*/ * @param content the current processing Content * @param sbPlain the StringBuffer to fill with text * @param attachmentList ArrayList with attachments * @throws UnsupportedEncodingException * @throws MessagingException * @throws IOException */ public static boolean handleParts(Message message, Object content, StringBuffer sbPlain, ArrayList<MessageAttachment> attachmentList) throws UnsupportedEncodingException, MessagingException, IOException { boolean isHTML = false; if (content instanceof String) { if (message.getContentType().toLowerCase().startsWith("text/html")) { isHTML = true; } else { isHTML = false; } sbPlain.append((String) content); } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; String multipartContentType = mp.getContentType().toLowerCase(); String text = null; if (multipartContentType.startsWith("multipart/alternative")) { isHTML = handleMultiPartAlternative(mp, sbPlain); } else { for (int i = 0; i < mp.getCount(); i++) { Part part = mp.getBodyPart(i); String contentType = part.getContentType().toLowerCase(); Boolean bodyRead = sbPlain.length() > 0; if (!bodyRead && contentType.startsWith("text/plain")) { isHTML = false; text = (String) part.getContent(); } else if (!bodyRead && contentType.startsWith("text/html")) { isHTML = true; text = (String) part.getContent(); } else if (!bodyRead && contentType.startsWith("message/rfc822")) { // Extract the message and pass it MimeMessage msg = (MimeMessage) part.getDataHandler().getContent(); isHTML = handleParts(msg, msg.getContent(), sbPlain, attachmentList); } else { if (part.getFileName() != null) { // Inline images are not added to the attachment // list // TODO: improve the in-line images detection if (part.getHeader("Content-ID") == null) { MessageAttachment attachment = new MessageAttachmentImpl(); attachment.setName(MimeUtility.decodeText(part.getFileName())); attachment.setContentType(part.getContentType()); attachment.setSize(part.getSize()); attachmentList.add(attachment); } } else { isHTML = handleParts(message, part.getContent(), sbPlain, attachmentList); } } } if (text != null) sbPlain.append(text); } } return isHTML; }
From source file:org.apache.hupa.server.utils.TestUtils.java
public static ArrayList<String> summaryzeContent(Object content, String contentType, final int spaces) throws IOException, MessagingException { ContenTypeArrayList ret = new ContenTypeArrayList(); ret.add(contentType, spaces);//from w w w .ja va 2 s . c o m if (content instanceof Multipart) { Multipart mp = (Multipart) content; contentType = mp.getContentType(); for (int i = 0; i < mp.getCount(); i++) { Part part = mp.getBodyPart(i); contentType = part.getContentType(); if (contentType.startsWith("text")) { ret.add(contentType, spaces + 1); } else if (contentType.startsWith("message/rfc822")) { MimeMessage msg = (MimeMessage) part.getDataHandler().getContent(); ret.addAll(summaryzeContent(msg.getContent(), msg.getContentType(), spaces + 1)); } else { if (part.getFileName() != null) { ret.add(part.getContentType(), part.getFileName(), spaces + 1); } else { ret.addAll(summaryzeContent(part.getContent(), contentType, spaces + 1)); } } } } return ret; }
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 a va 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; }
From source file:org.xwiki.platform.notifications.test.ui.NotificationsTest.java
@Test public void testNotificationsEmails() throws Exception { getUtil().login(SECOND_USER_NAME, SECOND_USER_PASSWORD); NotificationsUserProfilePage p;/*from w w w . j a v a 2s .c om*/ p = NotificationsUserProfilePage.gotoPage(SECOND_USER_NAME); p.setPageCreatedEmail(true); getUtil().login(FIRST_USER_NAME, FIRST_USER_PASSWORD); DocumentReference page1 = new DocumentReference("xwiki", getTestClassName(), "Page1"); DocumentReference page2 = new DocumentReference("xwiki", getTestClassName(), "Page2"); getUtil().createPage(getTestClassName(), "Page1", "Content 1", "Title 1"); getUtil().createPage(getTestClassName(), "Page2", "Content 2", "Title 2"); // Trigger the notification email job getUtil().login(SUPERADMIN_USER_NAME, SUPERADMIN_PASSWORD); SchedulerHomePage schedulerHomePage = SchedulerHomePage.gotoPage(); schedulerHomePage.clickJobActionTrigger("Notifications daily email"); this.mail.waitForIncomingEmail(1); assertEquals(1, this.mail.getReceivedMessages().length); MimeMessage message = this.mail.getReceivedMessages()[0]; assertTrue(message.getSubject().endsWith("event(s) on the wiki")); Multipart content = (Multipart) message.getContent(); assertTrue(content.getContentType().startsWith("multipart/mixed;")); assertEquals(1, content.getCount()); MimeBodyPart mimeBodyPart1 = (MimeBodyPart) content.getBodyPart(0); Multipart multipart1 = (Multipart) mimeBodyPart1.getContent(); assertEquals(2, multipart1.getCount()); assertEquals("text/plain; charset=UTF-8", multipart1.getBodyPart(0).getContentType()); assertEquals("text/html; charset=UTF-8", multipart1.getBodyPart(1).getContentType()); // Events inside an email comes in random order, so we just verify that all the expected content is there String email = prepareMail(multipart1.getBodyPart(0).getContent().toString()); assertTrue(email .contains(prepareMail(IOUtils.toString(getClass().getResourceAsStream("/expectedMail1.txt"))))); assertTrue(email .contains(prepareMail(IOUtils.toString(getClass().getResourceAsStream("/expectedMail2.txt"))))); assertTrue(email .contains(prepareMail(IOUtils.toString(getClass().getResourceAsStream("/expectedMail3.txt"))))); getUtil().rest().delete(page1); getUtil().rest().delete(page2); }