Example usage for javax.mail Part getContent

List of usage examples for javax.mail Part getContent

Introduction

In this page you can find the example usage for javax.mail Part getContent.

Prototype

public Object getContent() throws IOException, MessagingException;

Source Link

Document

Return the content as a Java object.

Usage

From source file:com.stimulus.archiva.domain.Email.java

protected boolean hasAttachment(Part p) throws MessagingException, IOException {

    if (p.getDisposition() != null && Compare.equalsIgnoreCase(p.getDisposition(), Part.ATTACHMENT)) {
        logger.debug("hasAttachment() attachment disposition.");
        return true;
    }/*from ww  w. j  ava  2s.  c  o  m*/
    if (p.getFileName() != null) {
        logger.debug("hasAttachment() filename specified.");
        return true;
    }

    try {
        if (p.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) p.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                logger.debug("hasAttachment() scanning multipart[" + i + "]");
                if (hasAttachment(mp.getBodyPart(i)))
                    return true;
            }
        } else if (p.isMimeType("message/rfc822")) {
            return hasAttachment((Part) p.getContent());
        }
    } catch (Exception e) {
        logger.debug("exception occurred while detecting attachment", e);
    }
    return false;
}

From source file:org.xwiki.contrib.mail.internal.JavamailMessageParser.java

/**
 * Recursively extracts content of an email. Every Part that has a file name, or is neither multipart, plain text or
 * html, is considered an attachment./*from   w  ww . j a va  2s .co  m*/
 * 
 * @param part
 * @return
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
public MailContent extractPartsContent(Part part) throws MessagingException, IOException {
    MailContent mailContent = new MailContent();

    String contentType = part.getContentType().toLowerCase();

    if (!StringUtils.isBlank(part.getFileName()) || (!contentType.startsWith("multipart/")
            && !part.isMimeType("text/plain") && !part.isMimeType("text/html"))) {
        mailContent.addAttachment((MimeBodyPart) part);
    } else if (part.isMimeType("text/plain")) {
        logger.debug("Extracting part PLAIN TEXT");
        mailContent.appendText(MimeUtility.decodeText((String) part.getContent()));
    } else if (part.isMimeType("text/html")) {
        logger.debug("Extracting part HTML");
        mailContent.appendHtml(MimeUtility.decodeText((String) part.getContent()));
    } else if (part.isMimeType("message/rfc822")) {
        logger.debug("Extracting part message/rfc822");
        Message innerMessage = (Message) part.getContent();
        mailContent.addAttachedMail(innerMessage);
        // FIXME attached mails should be loaded previously to their container
    } else if (contentType.startsWith("multipart/")) {
        logger.debug("Extracting MULTIPART");
        Multipart multipart = (Multipart) part.getContent();
        if (contentType.startsWith("multipart/signed")) {
            // Signed multiparts contain 2 parts: first is the content, second is the control information
            // We just ignore the control information
            logger.debug("Extracting SIGNED MULTIPART");
            mailContent.append(extractPartsContent(multipart.getBodyPart(0)));
        } else if (part.isMimeType("multipart/related") || part.isMimeType("multipart/mixed")
                || part.isMimeType("multipart/alternative")) {
            logger.debug("Extracting multipart / related or mixed or alternative");
            // FIXME multipart/alternative should be treated differently than other parts, though the same treatment
            // should be ok most of the time
            // (multipart/alternative is usually one part text/plain and the alternative text/html, so as text and
            // html
            // are always considered alternates by this algorithm, it's ok)
            int i = 0;
            int mcount = multipart.getCount();
            while (i < mcount) {
                logger.debug("Adding MULTIPART #{}", i);
                try {
                    final MailContent innerMailContent = extractPartsContent(multipart.getBodyPart(i));
                    mailContent.append(innerMailContent);
                } catch (Exception e) {
                    logger.warn("Could not add MULTIPART #{} because of {}", i, ExceptionUtils.getRootCause(e));
                }
                i++;
            }
        } else {
            logger.info("Multipart subtype {} not managed", contentType.substring(0, contentType.indexOf(' ')));
        }
    } else {
        logger.info("Message Type {} not managed", contentType.substring(0, contentType.indexOf('/')));
    }

    return mailContent;

}

From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * @param part//w  w  w  . j ava 2  s  . co m
 * @return
 * @throws Exception
 */
private String messageFromPart(Part part) throws Exception {

    if (part.isMimeType(GlobalConstants.MT_TEXT)) {

        String text = readPart(part);
        return text;

    } else if (part.isMimeType(GlobalConstants.MT_HTML)) {

        String text = readPart(part);
        return text;

    } else if (part.isMimeType(GlobalConstants.MT_MULTIPART)) {

        Multipart mp = (Multipart) part.getContent();
        return messageFromMultipart(mp);

    }

    return "";

}

From source file:com.liferay.mail.imap.IMAPAccessor.java

protected void getParts(long userId, StringBundler bodyPlain, StringBundler bodyHtml, String contentPath,
        Part part, List<MailFile> mailFiles) throws IOException, MessagingException {

    String fileName = part.getFileName();
    Object content = part.getContent();

    if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;

        for (int i = 0; i < multipart.getCount(); i++) {
            Part curPart = multipart.getBodyPart(i);

            getParts(userId, bodyPlain, bodyHtml,
                    contentPath.concat(StringPool.PERIOD).concat(String.valueOf(i)), curPart, mailFiles);
        }/* ww  w .ja  v a2  s  .  c o  m*/
    } else if (Validator.isNull(fileName)) {
        String contentType = StringUtil.toLowerCase(part.getContentType());

        if (contentType.startsWith(ContentTypes.TEXT_PLAIN)) {
            bodyPlain.append(content.toString().replaceAll("\r\n", "<br />"));
        } else if (contentType.startsWith(ContentTypes.TEXT_HTML)) {
            bodyHtml.append(HtmlContentUtil.getInlineHtml(content.toString()));
        }
        //else if (contentType.startsWith(ContentTypes.MESSAGE_RFC822)) {
        //}
    } else {
        MailFile mailFile = new MailFile(contentPath.concat(StringPool.PERIOD).concat("-1"), fileName,
                part.getSize());

        mailFiles.add(mailFile);
    }
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * This wrapper is used to work around a bug in the sun io inside
 * sun.io.ByteToCharConverter.getConverterClass(). The programmer uses 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 is documented. Thus, we need to
 * catch the undocumented exception.//from ww  w  .j  a v  a2 s .  c o m
 *
 * @param part The part from which to get the content.
 *
 * @return The content.
 *
 * @exception MessagingException if the content charset is unsupported.
 */
public static Object getPartContent(Part part) throws MessagingException {
    Object result = null;

    try {
        result = part.getContent();
    } catch (IllegalArgumentException ex) {
        throw new MessagingException("content charset is not recognized: " + ex.getMessage());
    } catch (IOException ex) {
        throw new MessagingException("getPartContent(): " + ex.getMessage());
    }

    return result;
}

From source file:org.apache.solr.handler.dataimport.FsMailEntityProcessor.java

public boolean addPartToDocument(Part part, Map<String, Object> row, boolean outerMost) throws Exception {
    if (outerMost && part instanceof Message) {
        if (!addEnvelopToDocument(part, row)) {
            return false;
        }/*  w  w  w .  j  a v a2  s  .  c  om*/
        // store hash
        row.put(HASH, DigestUtils.md5Hex((String) row.get(FROM_CLEAN) + "" + (String) row.get(SUBJECT)));
    }

    String ct = part.getContentType();
    ContentType ctype = new ContentType(ct);
    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        int count = mp.getCount();
        if (part.isMimeType("multipart/alternative")) {
            count = 1;
        }
        for (int i = 0; i < count; i++) {
            addPartToDocument(mp.getBodyPart(i), row, false);
        }
    } else if (part.isMimeType("message/rfc822")) {
        addPartToDocument((Part) part.getContent(), row, false);
    } else {
        String disp = part.getDisposition();
        @SuppressWarnings("resource") // Tika will close stream
        InputStream is = part.getInputStream();
        String fileName = part.getFileName();
        Metadata md = new Metadata();
        md.set(HttpHeaders.CONTENT_TYPE, ctype.getBaseType().toLowerCase(Locale.ROOT));
        md.set(TikaMetadataKeys.RESOURCE_NAME_KEY, fileName);
        String content = this.tika.parseToString(is, md);
        if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
            if (row.get(ATTACHMENT) == null) {
                row.put(ATTACHMENT, new ArrayList<String>());
            }
            List<String> contents = (List<String>) row.get(ATTACHMENT);
            contents.add(content);
            row.put(ATTACHMENT, contents);
            if (row.get(ATTACHMENT_NAMES) == null) {
                row.put(ATTACHMENT_NAMES, new ArrayList<String>());
            }
            List<String> names = (List<String>) row.get(ATTACHMENT_NAMES);
            names.add(fileName);
            row.put(ATTACHMENT_NAMES, names);
        } else {
            if (row.get(CONTENT) == null) {
                row.put(CONTENT, new ArrayList<String>());
            }
            List<String> contents = (List<String>) row.get(CONTENT);
            contents.add(content);
            row.put(CONTENT, contents);
        }
    }
    return true;
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

protected Part getPart(Part part, String contentPath) throws IOException, MessagingException {

    int index = GetterUtil.getInteger(StringUtil.split(contentPath.substring(1), StringPool.PERIOD)[0]);

    if (!(part.getContent() instanceof Multipart)) {
        return part;
    }/*w  ww .j  a  va  2 s  .  c om*/

    Multipart multipart = (Multipart) part.getContent();

    for (int i = 0; i < multipart.getCount(); i++) {
        if (i != index) {
            continue;
        }

        String prefix = String.valueOf(index).concat(StringPool.PERIOD);

        return getPart(multipart.getBodyPart(i), contentPath.substring(prefix.length()));
    }

    return part;
}

From source file:org.alfresco.repo.content.transform.EMLParser.java

/**
 * Adapted extract multipart is the recusrsive parser that splits the data and apend it to the
 * final xhtml file./*  w  ww  .j av a 2s. c o m*/
 *
 * @param xhtml
 *            the xhtml
 * @param part
 *            the part
 * @param parentPart
 *            the parent part
 * @param context
 *            the context
 * @throws MessagingException
 *             the messaging exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws SAXException
 *             the sAX exception
 * @throws TikaException
 *             the tika exception
 */
public void adaptedExtractMultipart(XHTMLContentHandler xhtml, Part part, Part parentPart, ParseContext context)
        throws MessagingException, IOException, SAXException, TikaException {

    String disposition = part.getDisposition();
    if ((disposition != null && disposition.contains(Part.ATTACHMENT))) {
        return;
    }

    if (part.isMimeType("text/plain")) {
        if (parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE)) {
            return;
        } else {
            // add file
            String data = part.getContent().toString();
            writeContent(part, data, MimetypeMap.MIMETYPE_TEXT_PLAIN, "txt");
        }
    } else if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        Part parentPartLocal = part;
        if (parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE)) {
            parentPartLocal = parentPart;
        }
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            adaptedExtractMultipart(xhtml, mp.getBodyPart(i), parentPartLocal, context);
        }
    } else if (part.isMimeType("message/rfc822")) {
        adaptedExtractMultipart(xhtml, (Part) part.getContent(), part, context);
    } else if (part.isMimeType("text/html")) {

        if ((parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE))
                || (part.getDisposition() == null || !part.getDisposition().contains(Part.ATTACHMENT))) {
            Object data = part.getContent();
            String htmlFileData = prepareString(new String(data.toString()));
            writeContent(part, htmlFileData, MimetypeMap.MIMETYPE_HTML, "html");
        }

    } else if (part.isMimeType("image/*")) {

        String[] encoded = part.getHeader("Content-Transfer-Encoding");
        if (isContained(encoded, "base64")) {
            if (part.getDisposition() != null && part.getDisposition().contains(Part.ATTACHMENT)) {
                InputStream stream = part.getInputStream();
                byte[] binaryData = new byte[part.getSize()];
                stream.read(binaryData, 0, part.getSize());
                String encodedData = new String(Base64.encodeBase64(binaryData));
                String[] split = part.getContentType().split(";");
                String src = "data:" + split[0].trim() + ";base64," + encodedData;
                AttributesImpl attributes = new AttributesImpl();
                attributes.addAttribute(null, "src", "src", "String", src);
                xhtml.startElement("img", attributes);
                xhtml.endElement("img");
            }
        }

    } else {
        Object content = part.getContent();
        if (content instanceof String) {
            xhtml.element("div", prepareString(part.getContent().toString()));
        } else if (content instanceof InputStream) {
            InputStream fileContent = part.getInputStream();

            Parser parser = new AutoDetectParser();
            Metadata attachmentMetadata = new Metadata();

            BodyContentHandler handlerAttachments = new BodyContentHandler();
            parser.parse(fileContent, handlerAttachments, attachmentMetadata, context);

            xhtml.element("div", handlerAttachments.toString());

        }
    }
}

From source file:dtw.webmail.model.JwmaMessagePartImpl.java

/**
 * Creates a <tt>JwmaMessagePartImpl</tt> instance from a given
 * <tt>javax.mail.Part</tt> instance.
 *
 * @param part a <tt>javax.mail.Part</tt> instance.
 * @param number the number of the part as <tt>int</tt>.
 *
 * @return the newly created instance.//from  w  w  w.j ava2 s .  co m
 * @throws JwmaException if it fails to create the new instance.
 */
public static JwmaMessagePartImpl createJwmaMessagePartImpl(Part part, int number) throws JwmaException {
    JwmaMessagePartImpl partinfo = new JwmaMessagePartImpl(part, number);

    //content type
    try {
        partinfo.setContentType(part.getContentType());

        //size
        int size = part.getSize();
        //JwmaKernel.getReference().debugLog().write("Part size="+size);
        String fileName = part.getFileName();
        //correct size of encoded parts
        String[] encoding = part.getHeader("Content-Transfer-Encoding");
        if (fileName != null && encoding != null && encoding.length > 0
                && (encoding[0].equalsIgnoreCase("base64") || encoding[0].equalsIgnoreCase("uuencode"))) {
            if ((fileName.startsWith("=?GB2312?B?") && fileName.endsWith("?="))) {
                byte[] decoded = Base64.decodeBase64(fileName.substring(11, fileName.indexOf("?=")).getBytes());
                fileName = new String(decoded, "GB2312");
                /*fileName = CipherUtils.decrypt(fileName);
                System.out.println("fileName----"+fileName);*/
                //fileName = getFromBASE64(fileName.substring(11,fileName.indexOf("?=")));  
            } else if ((fileName.startsWith("=?UTF-8?") || fileName.startsWith("=?UTF8?"))
                    && fileName.endsWith("?=")) {
                fileName = MimeUtility.decodeText(fileName);
            }
            //an encoded file is about 35% smaller in reality,
            //so correct the size
            size = (int) (size * 0.65);
        }

        partinfo.setSize(size);
        //description
        partinfo.setDescription(part.getDescription());

        //filename
        partinfo.setName(fileName);

        //textcontent
        if (partinfo.isMimeType("text/*")) {
            Object content = part.getContent();
            if (content instanceof String) {
                partinfo.setTextContent((String) content);
            } else if (content instanceof InputStream) {
                InputStream in = (InputStream) content;
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                byte[] buffer = new byte[8192];
                int amount = 0;
                while ((amount = in.read(buffer)) >= 0) {
                    bout.write(buffer, 0, amount);
                }
                partinfo.setTextContent(new String(bout.toString()));
            }
        }
    } catch (Exception mex) {
        throw new JwmaException("jwma.messagepart.failedcreation", true).setException(mex);
    }
    return partinfo;
}

From source file:com.glaf.mail.MxMailHelper.java

public void processPart(Part p, Mail mail) throws Exception {
    String contentType = p.getContentType();
    InputStream inputStream = null;
    try {// w w  w  . j a  va  2s  . c o m
        inputStream = new BufferedInputStream(p.getInputStream());
        if (contentType.startsWith("text/html")) {
            byte[] content = FileUtils.getBytes(inputStream);
            if (content != null && content.length > 0) {
                String html = new String(content);
                mail.setContent(html);
                mail.setMailType(TEXT_HTML);
            }
        } else if (contentType.startsWith("text/plain")) {
            byte[] content = FileUtils.getBytes(inputStream);
            if (content != null && content.length > 0) {
                mail.setContent(new String(content));
                mail.setMailType(TEXT_PLAIN);
            }
        } else if (contentType.startsWith("multipart") || contentType.startsWith("application/octet-stream")) {
            Multipart mp = (Multipart) p.getContent();
            processMultipart(mp, mail);
        }
    } catch (Exception ex) {
        throw ex;
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException ex) {
        }
    }

}