Example usage for javax.mail Multipart getBodyPart

List of usage examples for javax.mail Multipart getBodyPart

Introduction

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

Prototype

public synchronized BodyPart getBodyPart(int index) throws MessagingException 

Source Link

Document

Get the specified Part.

Usage

From source file:search.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message) {
        Message m = (Message) p;//from w  ww . ja  v a2s. c  om
        Address[] a;
        // FROM 
        if ((a = m.getFrom()) != null) {
            for (int j = 0; j < a.length; j++)
                System.out.println("FROM: " + a[j].toString());
        }

        // TO
        if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < a.length; j++)
                System.out.println("TO: " + a[j].toString());
        }

        // SUBJECT
        System.out.println("SUBJECT: " + m.getSubject());

        // DATE
        Date d = m.getSentDate();
        System.out.println("SendDate: " + (d != null ? d.toLocaleString() : "UNKNOWN"));

        // FLAGS:
        Flags flags = m.getFlags();
        StringBuffer sb = new StringBuffer();
        Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

        boolean first = true;
        for (int i = 0; i < sf.length; i++) {
            String s;
            Flags.Flag f = sf[i];
            if (f == Flags.Flag.ANSWERED)
                s = "\\Answered";
            else if (f == Flags.Flag.DELETED)
                s = "\\Deleted";
            else if (f == Flags.Flag.DRAFT)
                s = "\\Draft";
            else if (f == Flags.Flag.FLAGGED)
                s = "\\Flagged";
            else if (f == Flags.Flag.RECENT)
                s = "\\Recent";
            else if (f == Flags.Flag.SEEN)
                s = "\\Seen";
            else
                continue; // skip it
            if (first)
                first = false;
            else
                sb.append(' ');
            sb.append(s);
        }

        String[] uf = flags.getUserFlags(); // get the user flag strings
        for (int i = 0; i < uf.length; i++) {
            if (first)
                first = false;
            else
                sb.append(' ');
            sb.append(uf[i]);
        }
        System.out.println("FLAGS = " + sb.toString());
    }

    System.out.println("CONTENT-TYPE: " + p.getContentType());

    /* Dump input stream
    InputStream is = ((MimeMessage)m).getInputStream();
    int c;
    while ((c = is.read()) != -1)
        System.out.write(c);
    */

    Object o = p.getContent();
    if (o instanceof String) {
        System.out.println("This is a String");
        System.out.println((String) o);
    } else if (o instanceof Multipart) {
        System.out.println("This is a Multipart");
        Multipart mp = (Multipart) o;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
    } else if (o instanceof InputStream) {
        System.out.println("This is just an input stream");
        InputStream is = (InputStream) o;
        int c;
        while ((c = is.read()) != -1)
            System.out.write(c);
    }
}

From source file:search.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message) {
        Message m = (Message) p;//ww w  .j a  va2  s .  c  om
        Address[] a;
        // FROM
        if ((a = m.getFrom()) != null) {
            for (int j = 0; j < a.length; j++)
                System.out.println("FROM: " + a[j].toString());
        }

        // TO
        if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < a.length; j++)
                System.out.println("TO: " + a[j].toString());
        }

        // SUBJECT
        System.out.println("SUBJECT: " + m.getSubject());

        // DATE
        Date d = m.getSentDate();
        System.out.println("SendDate: " + (d != null ? d.toLocaleString() : "UNKNOWN"));

        // FLAGS:
        Flags flags = m.getFlags();
        StringBuffer sb = new StringBuffer();
        Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

        boolean first = true;
        for (int i = 0; i < sf.length; i++) {
            String s;
            Flags.Flag f = sf[i];
            if (f == Flags.Flag.ANSWERED)
                s = "\\Answered";
            else if (f == Flags.Flag.DELETED)
                s = "\\Deleted";
            else if (f == Flags.Flag.DRAFT)
                s = "\\Draft";
            else if (f == Flags.Flag.FLAGGED)
                s = "\\Flagged";
            else if (f == Flags.Flag.RECENT)
                s = "\\Recent";
            else if (f == Flags.Flag.SEEN)
                s = "\\Seen";
            else
                continue; // skip it
            if (first)
                first = false;
            else
                sb.append(' ');
            sb.append(s);
        }

        String[] uf = flags.getUserFlags(); // get the user flag strings
        for (int i = 0; i < uf.length; i++) {
            if (first)
                first = false;
            else
                sb.append(' ');
            sb.append(uf[i]);
        }
        System.out.println("FLAGS = " + sb.toString());
    }

    System.out.println("CONTENT-TYPE: " + p.getContentType());

    /*
     * Dump input stream InputStream is = ((MimeMessage)m).getInputStream(); int
     * c; while ((c = is.read()) != -1) System.out.write(c);
     */

    Object o = p.getContent();
    if (o instanceof String) {
        System.out.println("This is a String");
        System.out.println((String) o);
    } else if (o instanceof Multipart) {
        System.out.println("This is a Multipart");
        Multipart mp = (Multipart) o;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
    } else if (o instanceof InputStream) {
        System.out.println("This is just an input stream");
        InputStream is = (InputStream) o;
        int c;
        while ((c = is.read()) != -1)
            System.out.write(c);
    }
}

From source file:mitm.common.mail.MailUtils.java

/**
 * Converts any 8bit encoded parts to 7bit. Returns true if a part (or all parts) were converted from
 * 8bit to 7bit./*from w w  w .  j  a  va  2s  .co m*/
 * 
 * @param part
 * @throws MessagingException
 */
public static boolean convertTo7Bit(MimePart part) throws MessagingException, IOException {
    boolean converted = false;

    if (part.isMimeType("multipart/*")) {
        Multipart parts = (Multipart) part.getContent();

        int count = parts.getCount();

        for (int i = 0; i < count; i++) {
            boolean partConverted = convertTo7Bit((MimePart) parts.getBodyPart(i));

            if (partConverted) {
                converted = true;
            }
        }
    } else if ("8bit".equalsIgnoreCase(part.getEncoding())) {
        String encoding = part.isMimeType("text/*") ? "quoted-printable" : "base64";

        /*
         * We need to use a ByteArrayDataSource to make sure it will always be encoded
         */
        part.setDataHandler(
                new DataHandler(new ByteArrayDataSource(part.getInputStream(), part.getContentType())));

        part.setHeader("Content-Transfer-Encoding", encoding);
        part.addHeader("X-MIME-Autoconverted", "from 8bit to " + encoding + " by Djigzo");

        converted = true;
    }

    return converted;
}

From source file:org.apache.hupa.server.utils.MessageUtils.java

/**
 * Extract the attachments present in a mime message
 *
 * @param logger//from  www  .j a  va  2  s . c om
 * @param content
 * @return A list of body parts of the attachments
 * @throws MessagingException
 * @throws IOException
 */
static public List<BodyPart> extractMessageAttachments(Log logger, Object content)
        throws MessagingException, IOException {
    ArrayList<BodyPart> ret = new ArrayList<BodyPart>();
    if (content instanceof Multipart) {
        Multipart part = (Multipart) content;
        for (int i = 0; i < part.getCount(); i++) {
            BodyPart bodyPart = part.getBodyPart(i);
            String fileName = bodyPart.getFileName();
            String[] contentId = bodyPart.getHeader("Content-ID");
            if (bodyPart.isMimeType("multipart/*")) {
                ret.addAll(extractMessageAttachments(logger, bodyPart.getContent()));
            } else {
                if (contentId != null || fileName != null) {
                    ret.add(bodyPart);
                }
            }
        }
    } else {
        logger.error("Unknown content: " + content.getClass().getName());
    }
    return ret;
}

From source file:org.apache.hupa.server.utils.MessageUtils.java

/**
 * Loop over MuliPart and write the content to the Outputstream if a
 * attachment with the given name was found.
 *
 * @param logger/*  w  w  w .j a v a2 s  .  c o m*/
 *            The logger to use
 * @param content
 *            Content which should checked for attachments
 * @param attachmentName
 *            The attachmentname or the unique id for the searched attachment
 * @throws MessagingException
 * @throws IOException
 */
public static Part handleMultiPart(Log logger, Object content, String attachmentName)
        throws MessagingException, IOException {
    if (content instanceof Multipart) {
        Multipart part = (Multipart) content;
        for (int i = 0; i < part.getCount(); i++) {
            Part bodyPart = part.getBodyPart(i);
            String fileName = bodyPart.getFileName();
            String[] contentId = bodyPart.getHeader("Content-ID");
            if (bodyPart.isMimeType("multipart/*")) {
                Part p = handleMultiPart(logger, bodyPart.getContent(), attachmentName);
                if (p != null)
                    return p;
            } else {
                if (contentId != null) {
                    for (String id : contentId) {
                        id = id.replaceAll("^.*<(.+)>.*$", "$1");
                        System.out.println(attachmentName + " " + id);
                        if (attachmentName.equals(id))
                            return bodyPart;
                    }
                }
                if (fileName != null) {
                    if (cleanName(attachmentName).equalsIgnoreCase(cleanName(MimeUtility.decodeText(fileName))))
                        return bodyPart;
                }
            }
        }
    } else {
        logger.error("Unknown content: " + content.getClass().getName());
    }
    return null;
}

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

public static List<Attachment> getMessageAttachments(MimeMessage message) {

    List<Attachment> attachments = new LinkedList<>();

    try {// w  w w  . j a v a 2s.  co m

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

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

            if (bodyPart.getDisposition() != null
                    && bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
                byte[] content = IOUtils.toByteArray(bodyPart.getInputStream());
                attachments.add(new Attachment(bodyPart.getContentType(), bodyPart.getFileName(),
                        Base64.encodeBase64String(content)));
            }
        }

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

    return attachments;

}

From source file:mitm.common.mail.BodyPartUtils.java

private static String getPlainBodyAndAttachments(final Part part, Collection<Part> attachments, int level,
        int maxLevel) throws MessagingException, IOException {
    String body = null;/*from w w w  .j  a v  a2 s.c  om*/

    if (part.isMimeType("text/plain")) {
        body = (String) part.getContent();
    } else {
        /*
         * Maximum level deep
         */
        if (level <= maxLevel && part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();

            int partCount = mp.getCount();

            for (int i = 0; i < partCount; i++) {
                Part child = mp.getBodyPart(i);

                if (body == null) {
                    body = getPlainBodyAndAttachments(child, attachments, level + 1, maxLevel);

                    if (body == null && part.isMimeType("multipart/mixed")) {
                        if (attachments != null) {
                            attachments.add(child);
                        }
                    }
                } else if (part.isMimeType("multipart/mixed")) {
                    if (attachments != null) {
                        attachments.add(child);
                    }
                }
            }
        }
    }

    return body;
}

From source file:org.apache.axis.attachments.MimeUtils.java

/**
 * Determine as efficiently as possible the content length for attachments in a mail Multipart.
 * @param mp is the multipart to be serarched.
 * @return the actual length./*w  ww .ja  v a  2s .c o m*/
 *
 * @throws javax.mail.MessagingException
 * @throws java.io.IOException
 */
public static long getContentLength(javax.mail.Multipart mp)
        throws javax.mail.MessagingException, java.io.IOException {

    int totalParts = mp.getCount();
    long totalContentLength = 0;

    for (int i = 0; i < totalParts; ++i) {
        javax.mail.internet.MimeBodyPart bp = (javax.mail.internet.MimeBodyPart) mp.getBodyPart(i);

        totalContentLength += getContentLength(bp);
    }

    String ctype = mp.getContentType();
    javax.mail.internet.ContentType ct = new javax.mail.internet.ContentType(ctype);
    String boundaryStr = ct.getParameter("boundary");
    int boundaryStrLen = boundaryStr.length() + 4; // must add two for -- prefix and another two for crlf

    // there is one more boundary than parts
    // each parts data must have crlf after it.
    // last boundary has an additional --crlf
    return totalContentLength + boundaryStrLen * (totalParts + 1) + 2 * totalParts + +4;
}

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

private static Object fromMP(Multipart mp) throws Exception {
    ContentType ct = new ContentType(mp.getContentType());
    BodyPart bp;//  w w w .  j  av a  2 s. c o  m
    Object contents;
    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 {/*from   w w  w  .  ja  v a2s  .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;
}