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:mitm.common.security.smime.SMIMEUtils.java

/**
 * Returns the S/MIME type of the message (if S/MIME). It first checks the message headers to see if the
 * message can be a S/MIME message. If so it checks if it's a clear signed message by checking the
 * headers further. If it's not a clear signed message it will try to determine the CMS content type.
 *//* www. ja  va  2  s  . c  om*/
public static SMIMEType getSMIMEType(Part part) throws MessagingException, IOException {
    /* first check the headers */
    SMIMEHeader.Type headerType = SMIMEHeader.getSMIMEContentType(part);

    if (headerType == SMIMEHeader.Type.NO_SMIME) {
        return SMIMEType.NONE;
    }

    if (headerType == SMIMEHeader.Type.CLEAR_SIGNED || headerType == SMIMEHeader.Type.UNKNOWN_CLEAR_SIGNED) {
        Object content = part.getContent();

        if (!(content instanceof Multipart)) {
            logger.warn("Header says clear signed but content is not multipart.");

            return SMIMEType.NONE;
        }

        Multipart multipart = (Multipart) content;

        /* the content should be a multipart/mixed with 2 parts */
        BodyPart[] parts = SMIMEUtils.dissectSigned(multipart);

        if (parts == null) {
            if (headerType == SMIMEHeader.Type.CLEAR_SIGNED) {
                logger.warn("Header says s/mime but missing message part and/or signature part.");
            } else {
                logger.debug("Message is clear signed but not S/MIME signed.");
            }

            return SMIMEType.NONE;
        }

        CMSContentType cmsType = CMSContentTypeClassifier.getContentType(parts[1].getInputStream());

        /* check if the signed part is really a CMS structure */
        if (cmsType != CMSContentType.SIGNEDDATA) {
            logger.warn("Header says s/mime but signature part is not a valid CMS signed data.");

            return SMIMEType.NONE;
        }

        return SMIMEType.SIGNED;
    } else {
        /* check the CMS structure */
        CMSContentType cmsType = CMSContentTypeClassifier.getContentType(part.getInputStream());

        switch (cmsType) {
        case SIGNEDDATA:
            return SMIMEType.SIGNED;
        case ENVELOPEDDATA:
            return SMIMEType.ENCRYPTED;
        case COMPRESSEDDATA:
            return SMIMEType.COMPRESSED;
        default:
            break;
        }

        logger.warn("Header says s/mime but the message is not a valid CMS structure.");
    }

    return SMIMEType.NONE;
}

From source file:com.stimulus.archiva.extraction.MessageExtraction.java

private static String getTextContent(Part p) throws IOException, MessagingException {
    try {/* w ww.  j a v a 2  s. com*/
        return (String) p.getContent();
    } catch (UnsupportedEncodingException e) {
        OutputStream os = new ByteArrayOutputStream();
        p.writeTo(os);
        String raw = os.toString();
        os.close();

        //cp932 -> Windows-31J
        raw = raw.replaceAll("cp932", "Windows-31J");

        InputStream is = new ByteArrayInputStream(raw.getBytes());
        Part newPart = new MimeBodyPart(is);
        is.close();

        return (String) newPart.getContent();
    }
}

From source file:org.elasticsearch.river.email.EmailToJson.java

public static void saveAttachment(Part part, String destDir)
        throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
    if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();

        int partCount = multipart.getCount();
        for (int i = 0; i < partCount; i++) {

            BodyPart bodyPart = multipart.getBodyPart(i);

            String disp = bodyPart.getDisposition();
            if (disp != null
                    && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                InputStream is = bodyPart.getInputStream();
                saveFile(is, destDir, decodeText(bodyPart.getFileName()));
            } else if (bodyPart.isMimeType("multipart/*")) {
                saveAttachment(bodyPart, destDir);
            } else {
                String contentType = bodyPart.getContentType();
                if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                    saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                }// www .ja  v a 2  s .  c o m
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        saveAttachment((Part) part.getContent(), destDir);
    }
}

From source file:org.elasticsearch.river.email.EmailToJson.java

public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
    boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
    if (part.isMimeType("text/*") && !isContainTextAttach) {
        content.append(part.getContent().toString());
    } else if (part.isMimeType("message/rfc822")) {
        getMailTextContent((Part) part.getContent(), content);
    } else if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();
        int partCount = multipart.getCount();
        for (int i = 0; i < partCount; i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            getMailTextContent(bodyPart, content);
        }/*from w  ww  . ja  v a 2s. co  m*/
    }
}

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// w  ww .  j av  a  2 s.  co  m
 * @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:com.cubusmail.mail.util.MessageUtils.java

/**
 * @param part/*from ww w.  j ava  2 s  . co m*/
 * @return
 * @throws MessagingException
 * @throws IOException
 */
public static boolean hasAttachments(Part part) throws MessagingException, IOException {

    try {
        if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                MimeBodyPart bodyPart = (MimeBodyPart) mp.getBodyPart(i);
                if (Part.ATTACHMENT.equals(bodyPart.getDisposition())
                        || Part.INLINE.equals(bodyPart.getDisposition())) {
                    return true;
                }
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return false;
}

From source file:com.aurel.track.util.emailHandling.MailReader.java

public static StringBuffer handlePart(Part messagePart, List<EmailAttachment> attachments,
        boolean ignoreAttachments) {
    StringBuffer body = new StringBuffer();
    try {/*from   w  ww.j  av  a2 s. c  om*/
        Object content = messagePart.getContent();
        // Retrieve content type
        String contentType = messagePart.getContentType();
        LOGGER.debug("Content type is " + contentType);
        // Check if this is a multipart message
        if (content instanceof Multipart) {
            LOGGER.debug("(Multipart-Email)");
            String s = handleMultipart(messagePart, attachments, ignoreAttachments);
            if (s != null) {
                body.append(s);
            }
        } else {
            // process regular message
            String s = handleSimplePart(messagePart, attachments, ignoreAttachments);
            if (s != null) {
                body.append(s);
            }
        }
    } catch (Exception ex) {
        LOGGER.error(ExceptionUtils.getStackTrace(ex));
    }
    return body;
}

From source file:com.aurel.track.util.emailHandling.MailReader.java

private static String getText(Part part) throws MessagingException, IOException {
    String result = null;/*from w w w  . ja v a2s . c  o m*/
    if (part.isMimeType("text/plain")) {
        result = Text2HTML.addHTMLBreaks(StringEscapeUtils.escapeHtml((String) part.getContent()));

    } else if (part.isMimeType("text/html")) {
        result = part.getContent().toString();
    } else {
        LOGGER.debug("Process as text the part having mimeType:" + part.getContentType());
        result = Text2HTML.addHTMLBreaks(StringEscapeUtils.escapeHtml(part.getContent().toString()));
    }
    return result;
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

private static correoNoLeidos analizaParteDeMensaje2(correoNoLeidos correo, List<String> arc, List<String> rar,
        Part unaParte) {
    String r = null;//  ww w. j  a v  a  2 s.co  m
    try {
        System.out.println("CORREO NUM: ");
        // Si es multipart, se analiza cada una de sus partes recursivamente.
        if (unaParte.isMimeType("multipart/*")) {
            Multipart multi;
            multi = (Multipart) unaParte.getContent();
            System.out.println("for MULTIPART");
            for (int j = 0; j < multi.getCount(); j++) {
                System.out.println("Si es multi");
                analizaParteDeMensaje2(correo, arc, rar, multi.getBodyPart(j));
            }
        } else {
            // Si es texto, se escribe el texto.
            if (unaParte.isMimeType("text/*")) {
                System.out.println("Texto " + unaParte.getContentType());
                System.out.println(unaParte.getContent());
                System.out.println("---------------------------------");
                correo.setContenido((String) unaParte.getContent());
            }

            // Si es imagen, se guarda en fichero y se visualiza en JFrame
            if (unaParte.isMimeType("image/*")) {
                System.out.println("IMAGEN SYSTEM");
                System.out.println("Imagen " + unaParte.getContentType());
                System.out.println("Fichero=" + unaParte.getFileName());
                System.out.println("---------------------------------");

                arc.add("/Intranet/resources/archivosMail/verCorreo/" + salvaImagenEnFichero(unaParte));
                //visualizaImagenEnJFrame(unaParte);
            } else {
                System.out.println("ELSE img");
                // Si no es ninguna de las anteriores, se escribe en pantalla
                // el tipo.
                System.out.println("Recibido " + unaParte.getContentType());
                System.out.println("---------------------------------");
                if (salvaImagenEnFichero(unaParte) != null & salvaImagenEnFichero(unaParte) != "") {
                    rar.add(salvaImagenEnFichero(unaParte));
                }
                correo.setContenido((String) unaParte.getContent());
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    correo.setImagenes(arc);
    correo.setRar(rar);
    return correo;
}

From source file:org.nuxeo.cm.mail.actionpipe.ExtractMessageInformation.java

@SuppressWarnings("unchecked")
protected static void getAttachmentParts(Part p, String defaultFilename, MimetypeRegistry mimeService,
        ExecutionContext context) throws MessagingException, IOException {
    String filename = getFilename(p, defaultFilename);
    List<Blob> blobs = (List<Blob>) context.get(ATTACHMENTS_KEY);

    if (!p.isMimeType("multipart/*")) {
        String disp = p.getDisposition();
        // no disposition => consider it may be body
        if (disp == null && !context.containsKey(BODY_KEY)) {
            // this will need to be parsed
            context.put(BODY_KEY, p.getContent());
        } else if (disp != null
                && (disp.equalsIgnoreCase(Part.ATTACHMENT) || (disp.equalsIgnoreCase(Part.INLINE)
                        && !(p.isMimeType("text/*") || p.isMimeType("image/*"))))) {
            log.debug("Saving attachment to file " + filename);
            Blob blob = Blobs.createBlob(p.getInputStream());
            String mime = DEFAULT_BINARY_MIMETYPE;
            try {
                if (mimeService != null) {
                    ContentType contentType = new ContentType(p.getContentType());
                    mime = mimeService.getMimetypeFromFilenameAndBlobWithDefault(filename, blob,
                            contentType.getBaseType());
                }//www.ja v a  2 s . c o  m
            } catch (MimetypeDetectionException e) {
                log.error(e);
            }
            blob.setMimeType(mime);

            blob.setFilename(filename);

            blobs.add(blob);

            // for debug
            // File f = new File(filename);
            // ((MimeBodyPart) p).saveFile(f);

            log.debug("---------------------------");

        } else {
            log.debug(String.format("Ignoring part with type %s", p.getContentType()));
        }
    }

    if (p.isMimeType("multipart/*")) {
        log.debug("This is a Multipart");
        log.debug("---------------------------");
        Multipart mp = (Multipart) p.getContent();

        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            getAttachmentParts(mp.getBodyPart(i), defaultFilename, mimeService, context);
        }
    } else if (p.isMimeType(MESSAGE_RFC822_MIMETYPE)) {
        log.debug("This is a Nested Message");
        log.debug("---------------------------");
        getAttachmentParts((Part) p.getContent(), defaultFilename, mimeService, context);
    }

}