Example usage for javax.mail BodyPart getContent

List of usage examples for javax.mail BodyPart getContent

Introduction

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

Prototype

public Object getContent() throws IOException, MessagingException;

Source Link

Document

Return the content as a Java object.

Usage

From source file:net.prhin.mailman.MailMan.java

public static void main(String[] args) {
    Properties props = new Properties();
    props.setProperty(resourceBundle.getString("mailman.mail.store"),
            resourceBundle.getString("mailman.protocol"));

    Session session = Session.getInstance(props);

    try {//w  ww .j  a v  a2  s  . c o  m

        Store store = session.getStore();
        store.connect(resourceBundle.getString("mailman.host"), resourceBundle.getString("mailman.user"),
                resourceBundle.getString("mailman.password"));
        Folder inbox = store.getFolder(resourceBundle.getString("mailman.folder"));
        inbox.open(Folder.READ_ONLY);
        inbox.getUnreadMessageCount();
        Message[] messages = inbox.getMessages();

        for (int i = 0; i <= messages.length / 2; i++) {
            Message tmpMessage = messages[i];

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

            System.out.println("Multipart count: " + multipart.getCount());

            for (int j = 0; j < multipart.getCount(); j++) {
                BodyPart bodyPart = multipart.getBodyPart(j);

                if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
                    if (bodyPart.getContent().getClass().equals(MimeMultipart.class)) {
                        MimeMultipart mimeMultipart = (MimeMultipart) bodyPart.getContent();

                        for (int k = 0; k < mimeMultipart.getCount(); k++) {
                            if (mimeMultipart.getBodyPart(k).getFileName() != null) {
                                printFileContents(mimeMultipart.getBodyPart(k));
                            }
                        }
                    }
                } else {
                    printFileContents(bodyPart);
                }
            }
        }

        inbox.close(false);
        store.close();

    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:de.bht.fpa.mail.s000000.common.mail.imapsync.MessageConverter.java

private static void handleMultipart(Multipart content, MessageBuilder messageBuilder)
        throws MessagingException, IOException {
    for (int i = 0; i < content.getCount(); i++) {
        BodyPart bodyPart = content.getBodyPart(i);
        handleContent(bodyPart.getContent(), bodyPart, messageBuilder);
    }//from   w w  w. jav a2  s  .co  m
}

From source file:com.zotoh.crypto.MICUte.java

private static Object fromMP(Multipart mp) throws Exception {
    ContentType ct = new ContentType(mp.getContentType());
    BodyPart bp;
    Object contents;//  w w  w. j av a 2s  .  c om
    Object rc = null;
    int count = mp.getCount();

    if ("multipart/mixed".equalsIgnoreCase(ct.getBaseType())) {
        if (count > 0) {
            bp = mp.getBodyPart(0);
            contents = bp.getContent();

            // check for EDI payload sent as attachment
            String ctype = bp.getContentType();
            boolean getNextPart = false;

            if (ctype.indexOf("text/plain") >= 0) {
                if (contents instanceof String) {
                    String bodyText = "This is a generated cryptographic message in MIME format";
                    if (((String) contents).startsWith(bodyText)) {
                        getNextPart = true;
                    }
                }

                if (!getNextPart) {
                    // check for a content disposition
                    // if disposition type is attachment, then this is a doc
                    getNextPart = true;
                    String disp = bp.getDisposition();
                    if (disp != null && disp.toLowerCase().equals("attachment"))
                        getNextPart = false;
                }
            }

            if ((count >= 2) && getNextPart) {
                bp = mp.getBodyPart(1);
                contents = bp.getContent();
            }

            if (contents instanceof String) {
                rc = asBytes((String) contents);
            } else if (contents instanceof byte[]) {
                rc = contents;
            } else if (contents instanceof InputStream) {
                rc = contents;
            } else {
                String cn = contents == null ? "null" : contents.getClass().getName();
                throw new Exception("Unsupport MIC object: " + cn);
            }
        }
    } else if (count > 0) {
        bp = mp.getBodyPart(0);
        contents = bp.getContent();

        if (contents instanceof String) {
            rc = asBytes((String) contents);
        } else if (contents instanceof byte[]) {
            rc = contents;
        } else if (contents instanceof InputStream) {
            rc = contents;
        } else {
            String cn = contents == null ? "null" : contents.getClass().getName();
            throw new Exception("Unsupport MIC object: " + cn);
        }
    }

    return rc;
}

From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java

public static Body getMessageBody(MimeMessage message, String mimeType) {
    try {//w ww . ja v a  2 s  . c o m

        if (message.getContent() instanceof Multipart) {

            Multipart multipartMessage = (Multipart) message.getContent();

            for (int i = 0; i < multipartMessage.getCount(); i++) {
                BodyPart bodyPart = multipartMessage.getBodyPart(i);

                if (bodyPart.isMimeType(mimeType) && (Part.INLINE.equalsIgnoreCase(bodyPart.getDisposition())
                        || Objects.isNull(bodyPart.getDisposition()))) {

                    return new Body(bodyPart.getContentType(), bodyPart.getContent().toString());

                }
            }
        } else {

            return new Body(message.getContentType(), message.getContent().toString());
        }

    } catch (Exception e) {
        // do nothing
    }

    return null;
}

From source file:gov.nist.healthcare.ttt.parsing.Parsing.java

public static SOAPWithAttachment parseMtom(String mtom) throws MessagingException, IOException {

    //        Parsing.fixMissingEndBoundry(mtom);
    MimeMultipart mp;//from   w w  w .  ja  va 2 s . c  o m
    // String contentType = Parsing.findContentType(mtom);

    //     mp = new MimeMultipart(new ByteArrayDataSource(mtom.getBytes(), ""), new ContentType(contentType));
    mp = new MimeMultipart(new ByteArrayDataSource(mtom.getBytes(), "multipart/related"));
    SOAPWithAttachment swa = new SOAPWithAttachment();
    int count = mp.getCount();
    for (int i = 0; i < count; i++) {
        BodyPart bp = mp.getBodyPart(i);
        String contentType = bp.getContentType();
        if (contentType.startsWith("application/xop+xml")) {
            // SOAP
            ByteArrayInputStream content = (ByteArrayInputStream) bp.getContent();
            swa.setSoap(IOUtils.toString(content));

        } else {
            Object contentRaw = bp.getContent();
            if (contentRaw instanceof String) {
                String content = (String) bp.getContent();
                swa.getAttachment().add(content.getBytes());
            } else if (contentRaw instanceof SharedByteArrayInputStream) {
                SharedByteArrayInputStream content = (SharedByteArrayInputStream) bp.getContent();
                swa.getAttachment().add(read(content));
            } else {
                System.out.println("UNKNOWN ATTACHMENT TYPE = " + contentRaw.getClass().getName());
                swa.getAttachment().add(new String().getBytes());
            }
        }

        // System.out.println("contentype=" + bp.getContentType());
        //ByteArrayInputStream content = (ByteArrayInputStream) bp.getContent();
        //String contentString = IOUtils.toString(content);
        //String contentString = (String) bp.getContent();
        /*
        try {
        Envelope env = (Envelope) JAXB.unmarshal(new StringReader(contentString), Envelope.class);
        if (env.getHeader() == null && env.getBody() == null) {
            swa.getAttachment().add(Parsing.read(content));
            //swa.getAttachment().add(contentString.getBytes());
        } else {
            swa.setSoap(contentString);
        }
        } catch (Exception saxe) {
        // Not SOAP so must be attachment.
         swa.getAttachment().add(Parsing.read(content));
        //swa.getAttachment().add(contentString.getBytes());
        }
         */
    }

    if (swa.getAttachment() == null || swa.getAttachment().size() == 0) {
        byte[] document = Parsing.getDocumentFromSoap(swa.getSoap()).getBytes();
        Collection<byte[]> attachments = new ArrayList<byte[]>();
        attachments.add(document);
        swa.setAttachment(attachments);
    }

    return swa;
}

From source file:com.zimbra.cs.util.SpamExtract.java

private static void writeAttachedMessages(MimeMessage mm, File outdir, String msgUri)
        throws IOException, MessagingException {
    // Not raw - ignore the spam report and extract messages that are in attachments...
    if (!(mm.getContent() instanceof MimeMultipart)) {
        LOG.warn("Spam/notspam messages must have attachments (skipping " + msgUri + ")");
        return;//w w  w  .j  a  v  a2s .c om
    }

    MimeMultipart mmp = (MimeMultipart) mm.getContent();
    int nAttachments = mmp.getCount();
    boolean foundAtleastOneAttachedMessage = false;
    for (int i = 0; i < nAttachments; i++) {
        BodyPart bp = mmp.getBodyPart(i);
        if (!bp.isMimeType("message/rfc822")) {
            // Let's ignore all parts that are not messages.
            continue;
        }
        foundAtleastOneAttachedMessage = true;
        Part msg = (Part) bp.getContent(); // the actual message
        File file = new File(outdir, mOutputPrefix + "-" + mExtractIndex++);
        OutputStream os = null;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
            if (msg instanceof MimeMessage) {
                //bug 74435 clone into newMsg so our parser has a chance to handle headers which choke javamail
                ZMimeMessage newMsg = new ZMimeMessage((MimeMessage) msg);
                newMsg.writeTo(os);
            } else {
                msg.writeTo(os);
            }
        } finally {
            os.close();
        }
        if (verbose)
            LOG.info("Wrote: " + file);
    }

    if (!foundAtleastOneAttachedMessage) {
        String msgid = mm.getHeader("Message-ID", " ");
        LOG.warn("message uri=" + msgUri + " message-id=" + msgid + " had no attachments");
    }
}

From source file:fr.gouv.culture.vitam.eml.EmlExtract.java

private static final String handleMultipartRecur(Multipart mp, Element identification, String id,
        VitamArgument argument, ConfigLoader config) throws MessagingException, IOException {
    int count = mp.getCount();
    String result = "";
    for (int i = 0; i < count; i++) {
        BodyPart bp = mp.getBodyPart(i);
        Object content = bp.getContent();
        if (content instanceof String) {
            String[] cte = bp.getHeader("Content-Transfer-Encoding");
            String[] aresult = null;
            if (cte != null && cte.length > 0) {
                aresult = extractContentType(bp.getContentType(), cte[0]);
            } else {
                aresult = extractContentType(bp.getContentType(), null);
            }/*from  www .ja v  a  2  s.c o m*/
            Element emlroot = XmlDom.factory.createElement("body");
            // <identity format="Internet Message Format" mime="message/rfc822" puid="fmt/278" extensions="eml"/>
            Element subidenti = XmlDom.factory.createElement("identification");
            Element identity = XmlDom.factory.createElement("identity");
            identity.addAttribute("format", "Internet Message Body Format");
            identity.addAttribute("mime", aresult[0] != null ? aresult[0] : "unknown");
            identity.addAttribute("extensions", aresult[3] != null ? aresult[3].substring(1) : "unknown");
            if (aresult[1] != null) {
                identity.addAttribute("charset", aresult[1]);
            }
            identification.add(identity);
            emlroot.add(subidenti);
            identification.add(emlroot);
            //result += " " + saveBody((String) content.toString(), aresult, id, argument, config);
            result += " " + saveBody(bp.getInputStream(), aresult, id, argument, config);
            // ignore string
        } else if (content instanceof InputStream) {
            // handle input stream
            if (argument.extractKeyword) {
                result += " " + addSubIdentities(identification, bp, (InputStream) content, argument, config);
            } else {
                addSubIdentities(identification, bp, (InputStream) content, argument, config);
            }
        } else if (content instanceof Message) {
            Message message = (Message) content;
            if (argument.extractKeyword) {
                result += " " + handleMessageRecur(message, identification, id + "_" + i, argument, config);
            } else {
                handleMessageRecur(message, identification, id + "_" + i, argument, config);
            }
        } else if (content instanceof Multipart) {
            Multipart mp2 = (Multipart) content;
            if (argument.extractKeyword) {
                result += " " + handleMultipartRecur(mp2, identification, id + "_" + i, argument, config);
            } else {
                handleMultipartRecur(mp2, identification, id + "_" + i, argument, config);
            }
        }
    }
    return result;
}

From source file:fr.gouv.culture.vitam.eml.EmlExtract.java

private static final String handleMultipart(Multipart mp, Element identification, String id,
        VitamArgument argument, ConfigLoader config) throws MessagingException, IOException {
    int count = mp.getCount();
    String result = "";
    identification.addAttribute(EMAIL_FIELDS.attNumber.name, Integer.toString(count - 1));
    for (int i = 0; i < count; i++) {
        BodyPart bp = mp.getBodyPart(i);

        Object content = bp.getContent();
        if (content instanceof String) {
            String[] cte = bp.getHeader("Content-Transfer-Encoding");
            String[] aresult = null;
            if (cte != null && cte.length > 0) {
                aresult = extractContentType(bp.getContentType(), cte[0]);
            } else {
                aresult = extractContentType(bp.getContentType(), null);
            }/*w w  w. j  av a 2s.  c  om*/
            Element emlroot = XmlDom.factory.createElement("body");
            // <identity format="Internet Message Format" mime="message/rfc822" puid="fmt/278" extensions="eml"/>
            Element subidenti = XmlDom.factory.createElement("identification");
            Element identity = XmlDom.factory.createElement("identity");
            identity.addAttribute("format", "Internet Message Body Format");
            identity.addAttribute("mime", aresult[0] != null ? aresult[0] : "unknown");
            identity.addAttribute("extensions", aresult[3] != null ? aresult[3].substring(1) : "unknown");
            if (aresult[1] != null) {
                identity.addAttribute("charset", aresult[1]);
            }
            identification.add(identity);
            emlroot.add(subidenti);
            identification.add(emlroot);
            //result += " " + saveBody((String) content.toString(), aresult, id, argument, config);
            result += " " + saveBody(bp.getInputStream(), aresult, id, argument, config);
        } else if (content instanceof InputStream) {
            // handle input stream
            if (argument.extractKeyword) {
                result += " " + addSubIdentities(identification, bp, (InputStream) content, argument, config);
            } else {
                addSubIdentities(identification, bp, (InputStream) content, argument, config);
            }
            ((InputStream) content).close();
        } else if (content instanceof Message) {
            Message message = (Message) content;
            // XXX perhaps using Commands.addFormatIdentification
            Element emlroot = XmlDom.factory.createElement(EMAIL_FIELDS.formatEML.name);
            // <identity format="Internet Message Format" mime="message/rfc822" puid="fmt/278" extensions="eml"/>
            Element subidenti = XmlDom.factory.createElement("identification");
            Element identity = XmlDom.factory.createElement("identity");
            identity.addAttribute("format", "Internet Message Format");
            identity.addAttribute("mime", "message/rfc822");
            identity.addAttribute("puid", "fmt/278");
            identity.addAttribute("extensions", "eml");
            identification.add(identity);
            emlroot.add(subidenti);
            identification.add(emlroot);
            if (argument.extractKeyword) {
                result += " " + extractInfoMessage((MimeMessage) message, emlroot, argument, config);
            } else {
                extractInfoMessage((MimeMessage) message, emlroot, argument, config);
            }
        } else if (content instanceof Multipart) {
            Multipart mp2 = (Multipart) content;
            if (argument.extractKeyword) {
                result += " " + handleMultipartRecur(mp2, identification, id + "_" + i, argument, config);
            } else {
                handleMultipartRecur(mp2, identification, id + "_" + i, argument, config);
            }
        }
    }
    return result;
}

From source file:com.mirth.connect.connectors.http.HttpMessageConverter.java

private static void processContent(DonkeyElement contentElement, Object content, ContentType contentType,
        boolean parseMultipart, BinaryContentTypeResolver resolver)
        throws DonkeyElementException, MessagingException, IOException {
    if (resolver == null) {
        resolver = defaultResolver;/*w w  w .java  2 s.  c o  m*/
    }

    if (parseMultipart && content instanceof MimeMultipart) {
        contentElement.setAttribute("multipart", "yes");
        MimeMultipart multipart = (MimeMultipart) content;

        String boundary = contentType.getParameter("boundary");
        if (StringUtils.isNotBlank(boundary)) {
            contentElement.setAttribute("boundary", boundary);
        }

        if (StringUtils.isNotEmpty(multipart.getPreamble())) {
            contentElement.addChildElement("Preamble", multipart.getPreamble());
        }

        for (int partIndex = 0; partIndex < multipart.getCount(); partIndex++) {
            BodyPart part = multipart.getBodyPart(partIndex);
            DonkeyElement partElement = contentElement.addChildElement("Part");
            DonkeyElement headersElement = partElement.addChildElement("Headers");
            ContentType partContentType = contentType;

            for (Enumeration<javax.mail.Header> en = part.getAllHeaders(); en.hasMoreElements();) {
                javax.mail.Header header = en.nextElement();
                headersElement.addChildElement(header.getName(), header.getValue());

                if (header.getName().equalsIgnoreCase("Content-Type")) {
                    try {
                        partContentType = ContentType.parse(header.getValue());
                    } catch (RuntimeException e) {
                    }
                }
            }

            processContent(partElement.addChildElement("Content"), part.getContent(), partContentType, true,
                    resolver);
        }
    } else {
        contentElement.setAttribute("multipart", "no");
        String charset = getDefaultHttpCharset(
                contentType.getCharset() != null ? contentType.getCharset().name() : null);

        // Call the resolver to determine if the content should be Base64 encoded
        if (resolver.isBinaryContentType(contentType)) {
            contentElement.setAttribute("encoding", "Base64");
            byte[] contentByteArray = null;

            if (content instanceof StreamSource) {
                StreamSource streamSource = (StreamSource) content;
                if (streamSource.getInputStream() != null) {
                    contentByteArray = IOUtils.toByteArray(streamSource.getInputStream());
                } else if (streamSource.getReader() != null) {
                    contentByteArray = IOUtils.toString(streamSource.getReader()).getBytes(charset);
                }
            } else if (content instanceof InputStream) {
                contentByteArray = IOUtils.toByteArray((InputStream) content);
            } else if (content instanceof byte[]) {
                contentByteArray = (byte[]) content;
            }

            if (contentByteArray == null) {
                contentByteArray = (content != null ? content.toString() : "").getBytes(charset);
            }

            contentElement.setTextContent(new String(Base64Util.encodeBase64(contentByteArray), "US-ASCII"));
        } else {
            String contentText = null;

            if (content instanceof StreamSource) {
                StreamSource streamSource = (StreamSource) content;
                if (streamSource.getInputStream() != null) {
                    contentText = IOUtils.toString(streamSource.getInputStream(), charset);
                } else if (streamSource.getReader() != null) {
                    contentText = IOUtils.toString(streamSource.getReader());
                }
            } else if (content instanceof InputStream) {
                contentText = IOUtils.toString((InputStream) content, charset);
            } else if (content instanceof byte[]) {
                contentText = new String((byte[]) content, charset);
            }

            if (contentText == null) {
                contentText = content != null ? content.toString() : "";
            }

            contentElement.setTextContent(contentText);
        }
    }
}

From source file:com.adaptris.core.services.mime.FlattenMimeParts.java

private List<BodyPart> extract(Multipart m) throws Exception {
    List<BodyPart> parts = new ArrayList<>();
    for (int i = 0; i < m.getCount(); i++) {
        BodyPart p = m.getBodyPart(i);
        if (p.isMimeType("multipart/*")) {
            parts.addAll(extract((Multipart) p.getContent()));
        } else {/* ww  w.j  av a2  s.co m*/
            parts.add(p);
        }
    }
    return parts;
}