Example usage for javax.mail.internet MimeMultipart getBodyPart

List of usage examples for javax.mail.internet MimeMultipart getBodyPart

Introduction

In this page you can find the example usage for javax.mail.internet MimeMultipart getBodyPart.

Prototype

public synchronized BodyPart getBodyPart(String CID) throws MessagingException 

Source Link

Document

Get the MimeBodyPart referred to by the given ContentID (CID).

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 {//from ww w . ja  va  2s. co  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:Main.java

public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
    boolean flag = false;
    if (part.isMimeType("multipart/*")) {
        MimeMultipart multipart = (MimeMultipart) 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))) {
                flag = true;//  w ww.  j a va  2  s . com
            } else if (bodyPart.isMimeType("multipart/*")) {
                flag = isContainAttachment(bodyPart);
            } else {
                String contentType = bodyPart.getContentType();
                if (contentType.indexOf("application") != -1) {
                    flag = true;
                }

                if (contentType.indexOf("name") != -1) {
                    flag = true;
                }
            }

            if (flag)
                break;
        }
    } else if (part.isMimeType("message/rfc822")) {
        flag = isContainAttachment((Part) part.getContent());
    }
    return flag;
}

From source file:org.apache.james.postage.mail.MailMatchingUtils.java

public static int getMimePartSize(MimeMultipart parts, String mimeType) {
    if (parts != null) {
        try {/*from  ww w .j  a v  a2  s.c o  m*/
            for (int i = 0; i < parts.getCount(); i++) {
                BodyPart bodyPart = parts.getBodyPart(i);
                if (bodyPart.getContentType().startsWith(mimeType)) {
                    try {
                        Object content = bodyPart.getContent();
                        if (content instanceof InputStream) {
                            ByteArrayOutputStream os = new ByteArrayOutputStream();
                            IOUtils.copy(((InputStream) content), os);
                            return os.size();
                        } else if (content instanceof String) {
                            return ((String) content).length();
                        } else {
                            throw new IllegalStateException(
                                    "Unsupported content: " + content.getClass().toString());
                        }
                    } catch (IOException e) {
                        throw new IllegalStateException("Unexpected IOException in getContent()");
                    }
                }
            }
        } catch (MessagingException e) {
            log.info("failed to process body parts.", e);
        }
    }
    return 0;
}

From source file:org.mule.service.http.impl.service.server.grizzly.HttpParser.java

public static Collection<HttpPart> parseMultipartContent(InputStream content, String contentType)
        throws IOException {
    MimeMultipart mimeMultipart = null;
    List<HttpPart> parts = Lists.newArrayList();

    try {//from   w w w.j  a  v  a  2 s.  c o m
        mimeMultipart = new MimeMultipart(new ByteArrayDataSource(content, contentType));
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    try {
        int partCount = mimeMultipart.getCount();

        for (int i = 0; i < partCount; i++) {
            BodyPart part = mimeMultipart.getBodyPart(i);

            String filename = part.getFileName();
            String partName = filename;
            String[] contentDispositions = part.getHeader(CONTENT_DISPOSITION);
            if (contentDispositions != null) {
                String contentDisposition = contentDispositions[0];
                if (contentDisposition.contains(NAME_ATTRIBUTE)) {
                    partName = contentDisposition.substring(
                            contentDisposition.indexOf(NAME_ATTRIBUTE) + NAME_ATTRIBUTE.length() + 2);
                    partName = partName.substring(0, partName.indexOf("\""));
                }
            }

            if (partName == null && mimeMultipart.getContentType().contains(MULTIPART_RELATED.toString())) {
                String[] contentIdHeader = part.getHeader(CONTENT_ID);
                if (contentIdHeader != null && contentIdHeader.length > 0) {
                    partName = contentIdHeader[0];
                }
            }

            HttpPart httpPart = new HttpPart(partName, filename, IOUtils.toByteArray(part.getInputStream()),
                    part.getContentType(), part.getSize());

            Enumeration<Header> headers = part.getAllHeaders();

            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                httpPart.addHeader(header.getName(), header.getValue());
            }
            parts.add(httpPart);
        }
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    return parts;
}

From source file:mailbox.CreationViaEmail.java

private static Content getContentWithAttachments(MimePart part) throws MessagingException, IOException {
    Content result = new Content();
    String rootId = new ContentType(part.getContentType()).getParameter("start");
    MimeMultipart mp = (MimeMultipart) part.getContent();
    for (int i = 0; i < mp.getCount(); i++) {
        MimePart p = (MimePart) mp.getBodyPart(i);
        if (isRootPart(p, i, rootId)) {
            result = result.merge(processPart(p, part));
        } else {/*  w w  w  .  j  a v  a2s  .  c o m*/
            result.attachments.add(p);
        }
    }
    return result;
}

From source file:mailbox.CreationViaEmail.java

private static Content getJoinedContent(MimePart part) throws IOException, MessagingException {
    Content result = new Content();
    MimeMultipart mp = (MimeMultipart) part.getContent();
    for (int i = 0; i < mp.getCount(); i++) {
        MimeBodyPart p = (MimeBodyPart) mp.getBodyPart(i);
        result.merge(processPart(p, part));
    }/*from w  ww  .  jav a 2s. c  o m*/
    return result;
}

From source file:org.mule.module.http.internal.HttpParser.java

public static Collection<HttpPart> parseMultipartContent(InputStream content, String contentType)
        throws IOException {
    MimeMultipart mimeMultipart = null;
    List<HttpPart> parts = Lists.newArrayList();

    try {/*from   ww  w  .  jav  a 2 s  .  c  o m*/
        mimeMultipart = new MimeMultipart(new ByteArrayDataSource(content, contentType));
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    try {
        int partCount = mimeMultipart.getCount();

        for (int i = 0; i < partCount; i++) {
            BodyPart part = mimeMultipart.getBodyPart(i);

            String filename = part.getFileName();
            String partName = filename;
            String[] contentDispositions = part.getHeader(CONTENT_DISPOSITION_PART_HEADER);
            if (contentDispositions != null) {
                String contentDisposition = contentDispositions[0];
                if (contentDisposition.contains(NAME_ATTRIBUTE)) {
                    partName = contentDisposition.substring(
                            contentDisposition.indexOf(NAME_ATTRIBUTE) + NAME_ATTRIBUTE.length() + 2);
                    partName = partName.substring(0, partName.indexOf("\""));
                }
            }
            HttpPart httpPart = new HttpPart(partName, filename, IOUtils.toByteArray(part.getInputStream()),
                    part.getContentType(), part.getSize());

            Enumeration<Header> headers = part.getAllHeaders();

            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                httpPart.addHeader(header.getName(), header.getValue());
            }
            parts.add(httpPart);
        }
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    return parts;
}

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  ww  .  j a v a 2 s.  c  o  m*/
    }

    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:mailbox.CreationViaEmail.java

private static Content getContentOfBestPart(MimePart part, MimePart parent)
        throws IOException, MessagingException {
    MimeBodyPart best = null;//w  w  w. java2 s  .co m
    MimeMultipart mp = (MimeMultipart) part.getContent();
    for (int i = 0; i < mp.getCount(); i++) {
        // Prefer HTML if the parent is a multipart/related part which may contain
        // inline images, because text/plain cannot embed the images.
        boolean isHtmlPreferred = parent != null && parent.isMimeType(MimeType.MULTIPART_RELATED);
        best = better((MimeBodyPart) mp.getBodyPart(i), best, isHtmlPreferred);
    }
    return processPart(best, part);
}

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;/*www  .j av  a 2 s  .  c  om*/
    }

    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);
        }
    }
}