Example usage for javax.mail.internet MimePart getContentType

List of usage examples for javax.mail.internet MimePart getContentType

Introduction

In this page you can find the example usage for javax.mail.internet MimePart getContentType.

Prototype

public String getContentType() throws MessagingException;

Source Link

Document

Returns the Content-Type of the content of this part.

Usage

From source file:com.zimbra.cs.mime.MimeTest.java

@Test
public void pdfAsStream() throws Exception {
    String content = "From: user1@example.com\r\n" + "To: user2@example.com\r\n" + "Subject: test\r\n"
            + "Content-Type: application/octet-stream;name=\"test.pdf\"\r\n"
            + "Content-Transfer-Encoding: base64\r\n\r\n" + "R0a1231312ad124svsdsal=="; //obviously not a real pdf
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession(),
            new SharedByteArrayInputStream(content.getBytes()));

    MimePart part = Mime.getMimePart(mm, "1");
    Assert.assertEquals("application/octet-stream", Mime.getContentType(part.getContentType()));
}

From source file:com.zimbra.cs.mime.MimeTest.java

private void fileAsStream(String extension, boolean expectText) throws MessagingException, IOException {
    if (extension.charAt(0) == '.') {
        extension = extension.substring(1);
    }//  www  .  j av  a2 s . com
    String content = "From: user1@example.com\r\n" + "To: user2@example.com\r\n" + "Subject: test\r\n"
            + "Content-Type: application/octet-stream;name=\"test." + extension + "\"\r\n"
            + "Content-Transfer-Encoding: base64\r\n\r\n" + "R0a1231312ad124svsdsal=="; //obviously not a real file
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession(),
            new SharedByteArrayInputStream(content.getBytes()));

    MimePart part = Mime.getMimePart(mm, "1");
    String expectedType = expectText ? "text/plain" : "application/octet-stream";
    Assert.assertEquals(expectedType, Mime.getContentType(part.getContentType()));
}

From source file:com.zimbra.cs.mime.Mime.java

/** Returns a String containing the text content of the MimePart.  If the
 *  part's specified charset is unknown, defaults first to the user's
 *  preferred charset and then to the to the system's default charset.
 *  Use this method instead of {@link Part#getContent()} to work around
 *  JavaMail's fascism about proper MIME format and failure to support
 *  RFC 2184. *///ww w .  ja  v a2 s  .co m
public static String getStringContent(MimePart textPart, String defaultCharset)
        throws IOException, MessagingException {
    repairTransferEncoding(textPart);
    return decodeText(textPart.getInputStream(), textPart.getContentType(), defaultCharset);
}

From source file:com.zimbra.cs.mime.Mime.java

/** Returns a <tt>Reader</tt> for the text content of the <tt>MimePart</tt>.  If the
 *  part's specified charset is unknown, defaults first to the user's
 *  preferred charset and then to the to the system's default charset.
 *  Use this method instead of {@link Part#getContent()} to work around
 *  JavaMail's fascism about proper MIME format and failure to support
 *  RFC 2184.//from ww  w  .  ja va2  s .  com
 *
 *  @deprecated Use getTextReader() directly after calling repairTransferEncoding() as it's almost always
 *  necessary to drain and close the mimepart's input stream.
 *
 */

@Deprecated
public static Reader getContentAsReader(MimePart textPart, String defaultCharset)
        throws IOException, MessagingException {
    repairTransferEncoding(textPart);
    return getTextReader(textPart.getInputStream(), textPart.getContentType(), defaultCharset);
}

From source file:com.zimbra.cs.mime.Mime.java

private static MimeMultipart validateMultipart(MimeMultipart multi, MimePart mp)
        throws MessagingException, IOException {
    // our MIME parser preparses the multipart, so if an object exists then it's valid
    if (multi == null || isZimbraJavaMailShim(multi)) {
        return multi;
    }/*from w ww . j  a v  a 2 s  . c o m*/

    ContentType ctype = new ContentType(mp.getContentType());
    try {
        if (!ctype.containsParameter("generated") && !findStartBoundary(mp, ctype.getParameter("boundary"))) {
            return new ZMimeMultipart(new RawContentMultipartDataSource(mp, ctype));
        }
        multi.getCount();
    } catch (ParseException pe) {
        multi = new ZMimeMultipart(new FixedMultipartDataSource(mp, ctype));
    } catch (MessagingException me) {
        multi = new ZMimeMultipart(new FixedMultipartDataSource(mp, ctype));
    }
    return multi;
}

From source file:davmail.imap.ImapConnection.java

protected void appendBodyStructure(StringBuilder buffer, MimePart bodyPart)
        throws IOException, MessagingException {
    String contentType = MimeUtility.unfold(bodyPart.getContentType());
    int slashIndex = contentType.indexOf('/');
    if (slashIndex < 0) {
        throw new DavMailException("EXCEPTION_INVALID_CONTENT_TYPE", contentType);
    }//  w w  w . ja  v  a  2 s .c  o  m
    String type = contentType.substring(0, slashIndex).toUpperCase();
    buffer.append("(\"").append(type).append("\" \"");
    int semiColonIndex = contentType.indexOf(';');
    if (semiColonIndex < 0) {
        buffer.append(contentType.substring(slashIndex + 1).toUpperCase()).append("\" NIL");
    } else {
        // extended content type
        buffer.append(contentType.substring(slashIndex + 1, semiColonIndex).trim().toUpperCase()).append('\"');
        int charsetindex = contentType.indexOf("charset=");
        int nameindex = contentType.indexOf("name=");
        if (charsetindex >= 0 || nameindex >= 0) {
            buffer.append(" (");

            if (charsetindex >= 0) {
                buffer.append("\"CHARSET\" ");
                int charsetSemiColonIndex = contentType.indexOf(';', charsetindex);
                int charsetEndIndex;
                if (charsetSemiColonIndex > 0) {
                    charsetEndIndex = charsetSemiColonIndex;
                } else {
                    charsetEndIndex = contentType.length();
                }
                String charSet = contentType.substring(charsetindex + "charset=".length(), charsetEndIndex);
                if (!charSet.startsWith("\"")) {
                    buffer.append('"');
                }
                buffer.append(charSet.trim().toUpperCase());
                if (!charSet.endsWith("\"")) {
                    buffer.append('"');
                }
            }

            if (nameindex >= 0) {
                if (charsetindex >= 0) {
                    buffer.append(' ');
                }

                buffer.append("\"NAME\" ");
                int nameSemiColonIndex = contentType.indexOf(';', nameindex);
                int nameEndIndex;
                if (nameSemiColonIndex > 0) {
                    nameEndIndex = nameSemiColonIndex;
                } else {
                    nameEndIndex = contentType.length();
                }
                String name = contentType.substring(nameindex + "name=".length(), nameEndIndex).trim();
                if (!name.startsWith("\"")) {
                    buffer.append('"');
                }
                buffer.append(name.trim());
                if (!name.endsWith("\"")) {
                    buffer.append('"');
                }
            }
            buffer.append(')');
        } else {
            buffer.append(" NIL");
        }
    }
    appendBodyStructureValue(buffer, bodyPart.getContentID());
    appendBodyStructureValue(buffer, bodyPart.getDescription());
    appendBodyStructureValue(buffer, bodyPart.getEncoding());
    appendBodyStructureValue(buffer, bodyPart.getSize());
    if ("MESSAGE".equals(type) || "TEXT".equals(type)) {
        // line count not implemented in JavaMail, return fake line count
        appendBodyStructureValue(buffer, bodyPart.getSize() / 80);
    } else {
        // do not send line count for non text bodyparts
        appendBodyStructureValue(buffer, -1);
    }
    buffer.append(')');
}

From source file:com.icegreen.greenmail.store.SimpleMessageAttributes.java

/**
 * Parses key data items from a MimeMessage for seperate storage.
 * TODO this is a mess, and should be completely revamped.
 *///from w  w w.j ava 2s. c  om
void parseMimePart(MimePart part) throws MessagingException {
    size = GreenMailUtil.getBody(part).length();

    // Section 1 - Message Headers
    if (part instanceof MimeMessage) {
        try {
            subject = ((MimeMessage) part).getSubject();
        } catch (MessagingException me) {
            //                if (DEBUG) getLogger().debug("Messaging Exception for getSubject: " + me);
        }
    }
    try {
        from = part.getHeader("From");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(From): " + me);
    }
    try {
        sender = part.getHeader("Sender");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Sender): " + me);
    }
    try {
        replyTo = part.getHeader("Reply To");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Reply To): " + me);
    }
    try {
        to = part.getHeader("To");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me);
    }
    try {
        cc = part.getHeader("Cc");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me);
    }
    try {
        bcc = part.getHeader("Bcc");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me);
    }
    try {
        inReplyTo = part.getHeader("In Reply To");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(In Reply To): " + me);
    }
    try {
        date = part.getHeader("Date");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Date): " + me);
    }
    try {
        messageID = part.getHeader("Message-ID");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(messageID): " + me);
    }
    String contentTypeLine = null;
    try {
        contentTypeLine = part.getContentType();
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getContentType(): " + me);
    }
    if (contentTypeLine != null) {
        decodeContentType(contentTypeLine);
    }
    try {
        contentID = part.getContentID();
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getContentUD(): " + me);
    }
    try {
        contentDesc = part.getDescription();
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getDescription(): " + me);
    }
    try {
        contentEncoding = part.getEncoding();
        // default value.
        if (contentEncoding == null) {
            contentEncoding = "7BIT";
        }
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getEncoding(): " + me);
    }

    try {
        //            contentDisposition = part.getDisposition();
        contentDisposition = Header.create(part.getHeader("Content-Disposition"));
    } catch (MessagingException me) {
        if (log.isDebugEnabled()) {
            log.debug("Can not create content disposition for part " + part, me);
        }
    }

    try {
        // TODO this doesn't work
        lineCount = getLineCount(part);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Can not get line count for part " + part, e);
        }
    }

    // Recurse through any embedded parts
    if (primaryType.equalsIgnoreCase(MULTIPART)) {
        MimeMultipart container;
        try {
            container = (MimeMultipart) part.getContent();
            int count = container.getCount();
            parts = new SimpleMessageAttributes[count];
            for (int i = 0; i < count; i++) {
                BodyPart nextPart = container.getBodyPart(i);

                if (nextPart instanceof MimePart) {
                    SimpleMessageAttributes partAttrs = new SimpleMessageAttributes(null, receivedDate);
                    partAttrs.parseMimePart((MimePart) nextPart);
                    parts[i] = partAttrs;

                }
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Can not recurse through multipart content", e);
            }
        }
    } else if (primaryType.equalsIgnoreCase("message")) {
        if (secondaryType.equalsIgnoreCase("RFC822")) {
            //try {

            /*
            MimeMessageWrapper message = new MimeMessageWrapper(part.getInputStream());
            SimpleMessageAttributes msgAttrs = new SimpleMessageAttributes();
            msgAttrs.setAttributesFor(message);
                    
            if (part instanceof MimeMessage) {
            Comments out because I don't know what it should do here
            MimeMessage msg1 = (MimeMessage) part;
            MimeMessageWrapper message2 = new MimeMessageWrapper(msg1);
            SimpleMessageAttributes msgAttrs2 = new SimpleMessageAttributes();
            msgAttrs.setAttributesFor(message2);
            }
                    
            parts = new SimpleMessageAttributes[1];
            parts[0] = msgAttrs;
            */
            //} catch (Exception e) {
            //getLogger().error("Error interpreting a message/rfc822: " + e);
            //e.printStackTrace();
            //}

            // TODO: Warn till fixed!
            log.warn("Unknown/unhandled subtype " + secondaryType + " of message encountered.");
        } else {
            log.warn("Unknown/unhandled subtype " + secondaryType + " of message encountered.");
        }
    }
}

From source file:com.zimbra.cs.mime.Mime.java

private static List<MPartInfo> listParts(MimePart root, String defaultCharset)
        throws MessagingException, IOException {
    List<MPartInfo> parts = new ArrayList<MPartInfo>();

    LinkedList<MPartInfo> queue = new LinkedList<MPartInfo>();
    queue.add(generateMPartInfo(root, null, "", 0));

    MimeMultipart emptyMultipart = null;
    while (!queue.isEmpty()) {
        MPartInfo mpart = queue.removeFirst();
        MimePart mp = mpart.getMimePart();
        parts.add(mpart);//from  w  w  w.  ja  v a2 s. co m

        String cts = mpart.mContentType;
        boolean isMultipart = cts.startsWith(MimeConstants.CT_MULTIPART_PREFIX);
        boolean isMessage = !isMultipart && cts.equals(MimeConstants.CT_MESSAGE_RFC822);

        if (isMultipart) {
            // IMAP part numbering is screwy: top-level multipart doesn't get a number
            String prefix = mpart.mPartName.length() > 0 ? (mpart.mPartName + '.') : "";
            if (mp instanceof MimeMessage) {
                mpart.mPartName = prefix + "TEXT";
            }
            MimeMultipart multi = getMultipartContent(mp, cts);
            if (multi != null) {
                if (multi.getCount() == 0 && LC.mime_promote_empty_multipart.booleanValue()) {
                    if (emptyMultipart == null) {
                        emptyMultipart = multi;
                    }
                    if (MimeConstants.CT_MULTIPART_APPLEDOUBLE.equalsIgnoreCase(getContentType(mp))) {
                        ZimbraLog.misc.debug(
                                "appledouble with no children; assuming it is malformed and really applefile");
                        mpart.mContentType = mpart.mContentType.replace(MimeConstants.CT_MULTIPART_APPLEDOUBLE,
                                MimeConstants.CT_APPLEFILE);
                    }
                }
                mpart.mChildren = new ArrayList<MPartInfo>(multi.getCount());
                for (int i = 1; i <= multi.getCount(); i++) {
                    mpart.mChildren
                            .add(generateMPartInfo((MimePart) multi.getBodyPart(i - 1), mpart, prefix + i, i));
                }
                queue.addAll(0, mpart.mChildren);
            }
        } else if (isMessage) {
            MimeMessage mm = getMessageContent(mp);
            if (mm != null) {
                MPartInfo child = generateMPartInfo(mm, mpart, mpart.mPartName, 0);
                queue.addFirst(child);
                mpart.mChildren = Arrays.asList(child);
            }
        } else {
            // nothing to do at this stage
        }
    }

    if (emptyMultipart != null && parts.size() == 1) {
        String text = emptyMultipart.getPreamble();
        if (!StringUtil.isNullOrEmpty(text)) {
            ZimbraLog.misc
                    .debug("single multipart with no children. promoting the preamble into a single text part");
            parts.remove(0);
            MPartInfo mpart = new MPartInfo();
            ZMimeBodyPart mp = new ZMimeBodyPart();
            mp.setText(text, defaultCharset);
            mpart.mPart = mp;
            mpart.mContentType = mp.getContentType();
            mpart.mDisposition = "";
            mpart.mPartName = "1";
            parts.add(mpart);
        }
    }

    return parts;
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * Create message in specified folder.//  www .j  a va 2s. c  o  m
 * Will overwrite an existing message with same messageName in the same folder
 *
 * @param folderPath  Exchange folder path
 * @param messageName message name
 * @param properties  message properties (flags)
 * @param mimeMessage MIME message
 * @throws IOException when unable to create message
 */
@Override
public void createMessage(String folderPath, String messageName, HashMap<String, String> properties,
        MimeMessage mimeMessage) throws IOException {
    String messageUrl = URIUtil.encodePathQuery(getFolderPath(folderPath) + '/' + messageName);
    PropPatchMethod patchMethod;
    List<PropEntry> davProperties = buildProperties(properties);

    if (properties != null && properties.containsKey("draft")) {
        // note: draft is readonly after create, create the message first with requested messageFlags
        davProperties.add(Field.createDavProperty("messageFlags", properties.get("draft")));
    }
    if (properties != null && properties.containsKey("mailOverrideFormat")) {
        davProperties.add(Field.createDavProperty("mailOverrideFormat", properties.get("mailOverrideFormat")));
    }
    if (properties != null && properties.containsKey("messageFormat")) {
        davProperties.add(Field.createDavProperty("messageFormat", properties.get("messageFormat")));
    }
    if (!davProperties.isEmpty()) {
        patchMethod = new PropPatchMethod(messageUrl, davProperties);
        try {
            // update message with blind carbon copy and other flags
            int statusCode = httpClient.executeMethod(patchMethod);
            if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ',
                        patchMethod.getStatusLine());
            }

        } finally {
            patchMethod.releaseConnection();
        }
    }

    // update message body
    PutMethod putmethod = new PutMethod(messageUrl);
    putmethod.setRequestHeader("Translate", "f");
    putmethod.setRequestHeader("Content-Type", "message/rfc822");

    try {
        // use same encoding as client socket reader
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        mimeMessage.writeTo(baos);
        baos.close();
        putmethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
        int code = httpClient.executeMethod(putmethod);

        // workaround for misconfigured Exchange server
        if (code == HttpStatus.SC_NOT_ACCEPTABLE) {
            LOGGER.warn(
                    "Draft message creation failed, failover to property update. Note: attachments are lost");

            ArrayList<PropEntry> propertyList = new ArrayList<PropEntry>();
            propertyList.add(Field.createDavProperty("to", mimeMessage.getHeader("to", ",")));
            propertyList.add(Field.createDavProperty("cc", mimeMessage.getHeader("cc", ",")));
            propertyList.add(Field.createDavProperty("message-id", mimeMessage.getHeader("message-id", ",")));

            MimePart mimePart = mimeMessage;
            if (mimeMessage.getContent() instanceof MimeMultipart) {
                MimeMultipart multiPart = (MimeMultipart) mimeMessage.getContent();
                for (int i = 0; i < multiPart.getCount(); i++) {
                    String contentType = multiPart.getBodyPart(i).getContentType();
                    if (contentType.startsWith("text/")) {
                        mimePart = (MimePart) multiPart.getBodyPart(i);
                        break;
                    }
                }
            }

            String contentType = mimePart.getContentType();

            if (contentType.startsWith("text/plain")) {
                propertyList.add(Field.createDavProperty("description", (String) mimePart.getContent()));
            } else if (contentType.startsWith("text/html")) {
                propertyList.add(Field.createDavProperty("htmldescription", (String) mimePart.getContent()));
            } else {
                LOGGER.warn("Unsupported content type: " + contentType + " message body will be empty");
            }

            propertyList.add(Field.createDavProperty("subject", mimeMessage.getHeader("subject", ",")));
            PropPatchMethod propPatchMethod = new PropPatchMethod(messageUrl, propertyList);
            try {
                int patchStatus = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, propPatchMethod);
                if (patchStatus == HttpStatus.SC_MULTI_STATUS) {
                    code = HttpStatus.SC_OK;
                }
            } finally {
                propPatchMethod.releaseConnection();
            }
        }

        if (code != HttpStatus.SC_OK && code != HttpStatus.SC_CREATED) {

            // first delete draft message
            if (!davProperties.isEmpty()) {
                try {
                    DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, messageUrl);
                } catch (IOException e) {
                    LOGGER.warn("Unable to delete draft message");
                }
            }
            if (code == HttpStatus.SC_INSUFFICIENT_STORAGE) {
                throw new InsufficientStorageException(putmethod.getStatusText());
            } else {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, code, ' ',
                        putmethod.getStatusLine());
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    } finally {
        putmethod.releaseConnection();
    }

    try {
        // need to update bcc after put
        if (mimeMessage.getHeader("Bcc") != null) {
            davProperties = new ArrayList<PropEntry>();
            davProperties.add(Field.createDavProperty("bcc", mimeMessage.getHeader("Bcc", ",")));
            patchMethod = new PropPatchMethod(messageUrl, davProperties);
            try {
                // update message with blind carbon copy
                int statusCode = httpClient.executeMethod(patchMethod);
                if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                    throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode,
                            ' ', patchMethod.getStatusLine());
                }

            } finally {
                patchMethod.releaseConnection();
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }

}

From source file:com.zimbra.cs.service.mail.ToXML.java

/** Adds the decoded text content of a message part to the {@link Element}.
 *  The content is added as the value of a new <tt>&lt;content></tt>
 *  sub-element.  <i>Note: This method will only extract the content of a
 *  <b>text/*</b> or <b>xml/*</b> message part.</i>
 *
 * @param elt     The element to add the <tt>&lt;content></tt> to.
 * @param mpi     The message part to extract the content from.
 * @param maxSize The maximum number of characters to inline (<=0 is unlimited).
 * @param neuter  Whether to "neuter" image <tt>src</tt> attributes.
 * @parame defaultCharset  The user's default charset preference.
 * @throws MessagingException when message parsing or CTE-decoding fails
 * @throws IOException on error during parsing or defanging
 * @see HtmlDefang#defang(String, boolean) */
private static void addContent(Element elt, MPartInfo mpi, int maxSize, boolean neuter, String defaultCharset,
        MsgContent wantContent) throws IOException, MessagingException {
    // TODO: support other parts
    String ctype = mpi.getContentType();
    if (!ctype.matches(MimeConstants.CT_TEXT_WILD) && !ctype.matches(MimeConstants.CT_XML_WILD)) {
        return;/*ww  w.  jav  a2 s .  co  m*/
    }
    MimePart mp = mpi.getMimePart();
    Mime.repairTransferEncoding(mp);

    String data = null;
    String originalContent = null;
    wantContent = wantContent == null ? MsgContent.full : wantContent;
    try {
        if (maxSize <= 0) {
            maxSize = (int) Provisioning.getInstance().getLocalServer().getMailContentMaxSize();
        } else {
            maxSize = Math.min(maxSize,
                    (int) Provisioning.getInstance().getLocalServer().getMailContentMaxSize());
        }
    } catch (ServiceException e) {
        ZimbraLog.soap.warn("Unable to determine max content size", e);
    }

    boolean wasTruncated = false;
    if (ctype.equals(MimeConstants.CT_TEXT_HTML)) {
        String charset = mpi.getContentTypeParameter(MimeConstants.P_CHARSET);
        InputStream stream = null;
        StringWriter sw = new StringWriter();
        TruncatingWriter tw = null;
        Writer out = sw;
        if (maxSize > 0) {
            tw = new TruncatingWriter(sw, maxSize + 1);
            out = tw;
        }
        Reader reader = null;

        try {
            stream = mp.getInputStream();
            if (charset != null && !charset.trim().isEmpty()) {
                // make sure to feed getTextReader() a full Content-Type header, not just the primary/subtype portion
                reader = Mime.getTextReader(stream, mp.getContentType(), defaultCharset);
                BrowserDefang defanger = DefangFactory.getDefanger(mp.getContentType());
                defanger.defang(reader, neuter, out);
                data = sw.toString();
            } else {
                String cte = mp.getEncoding();
                if (cte != null && !cte.trim().toLowerCase().equals(MimeConstants.ET_7BIT)) {
                    try {
                        DefangFactory.getDefanger(ctype).defang(stream, neuter, out);
                        data = sw.toString();
                    } catch (IOException e) {
                    }
                }
                if (data == null) {
                    reader = Mime.getTextReader(stream, mp.getContentType(), defaultCharset);
                    DefangFactory.getDefanger(ctype).defang(reader, neuter, out);
                    data = sw.toString();
                }
            }
            if (wantContent.equals(MsgContent.original) || wantContent.equals(MsgContent.both)) {
                originalContent = removeQuotedText(data, true);
            }
        } finally {
            if (tw != null) {
                wasTruncated = tw.wasTruncated();
            }
            ByteUtil.closeStream(stream);
            Closeables.closeQuietly(reader);
        }
    } else if (ctype.equals(MimeConstants.CT_TEXT_ENRICHED)) {
        // Enriched text handling is a little funky because TextEnrichedHandler
        // doesn't use Reader and Writer.  As a result, we truncate
        // the source before converting to HTML.
        InputStream stream = mp.getInputStream();
        Reader reader = null;
        try {
            reader = Mime.getTextReader(stream, mp.getContentType(), defaultCharset);
            int maxChars = (maxSize > 0 ? maxSize + 1 : -1);
            String enriched = ByteUtil.getContent(reader, maxChars, false);
            if (enriched.length() == maxChars) {
                // The normal check for truncated data won't work because
                // the length of the converted text is different than the length
                // of the source, so set the attr here.
                wasTruncated = true;
            }
            if (wantContent.equals(MsgContent.original) || wantContent.equals(MsgContent.both)) {
                originalContent = TextEnrichedHandler.convertToHTML(removeQuotedText(enriched, false));
            }
            data = TextEnrichedHandler.convertToHTML(enriched);
        } finally {
            ByteUtil.closeStream(stream);
            Closeables.closeQuietly(reader);
        }
    } else {
        InputStream stream = mp.getInputStream();
        Reader reader = null;
        try {
            reader = Mime.getTextReader(stream, mp.getContentType(), defaultCharset);
            int maxChars = (maxSize > 0 ? maxSize + 1 : -1);
            data = ByteUtil.getContent(reader, maxChars, false);
            if (wantContent.equals(MsgContent.original) || wantContent.equals(MsgContent.both)) {
                originalContent = removeQuotedText(data, false);
            }
            if (data.length() == maxChars) {
                wasTruncated = true;
            }
        } finally {
            ByteUtil.closeStream(stream);
            Closeables.closeQuietly(reader);
        }
    }

    if (data != null && !wantContent.equals(MsgContent.original)) {
        data = StringUtil.stripControlCharacters(data);
        if (wasTruncated) {
            elt.addAttribute(MailConstants.A_TRUNCATED_CONTENT, true);
            if (data.length() > maxSize) {
                data = data.substring(0, maxSize);
            }
        }
        elt.addAttribute(MailConstants.E_CONTENT, data, Element.Disposition.CONTENT);
    }
    if (originalContent != null
            && (wantContent.equals(MsgContent.original) || wantContent.equals(MsgContent.both))) {
        originalContent = StringUtil.stripControlCharacters(originalContent);
        elt.addUniqueElement(MailConstants.E_ORIG_CONTENT).setText(originalContent);
    }
    // TODO: CDATA worth the effort?
}