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:org.apache.hupa.server.utils.MessageUtils.java

private static boolean handleMultiPartAlternative(Multipart mp, StringBuffer sbPlain)
        throws MessagingException, IOException {
    String text = null;//from  w  w  w . jav a 2 s  .  c  o m
    boolean isHTML = false;
    for (int i = 0; i < mp.getCount(); i++) {
        Part part = mp.getBodyPart(i);

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

        // we prefer html
        if (text == null && contentType.startsWith("text/plain")) {
            isHTML = false;
            text = (String) part.getContent();
        } else if (contentType.startsWith("text/html")) {
            isHTML = true;
            text = (String) part.getContent();
        }
    }
    sbPlain.append(text);
    return isHTML;
}

From source file:com.email.ReceiveEmail.java

/**
 * Save the attachments from the email/*  w w w  .ja v a 2s. com*/
 *
 * @param p Part
 * @param m Message
 * @param eml EmailMessageModel
 */
private static void saveAttachments(Part p, Message m, EmailMessageModel eml) {
    try {
        String filename = p.getFileName();
        if (filename != null && !filename.endsWith("vcf")) {
            try {
                saveFile(p, filename, eml);
            } catch (ClassCastException ex) {
                System.err.println("CRASH");
            }
        } else if (p.isMimeType("IMAGE/*")) {
            saveFile(p, filename, eml);
        }
        if (p.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) p.getContent();
            int pageCount = mp.getCount();
            for (int i = 0; i < pageCount; i++) {
                saveAttachments(mp.getBodyPart(i), m, eml);
            }
        } else if (p.isMimeType("message/rfc822")) {
            saveAttachments((Part) p.getContent(), m, eml);
        }
    } catch (IOException | MessagingException ex) {
        ExceptionHandler.Handle(ex);
    }
}

From source file:org.jevis.emaildatasource.EMailManager.java

/**
 * Find attachment and save it in inputstream
 *
 * @param message EMail message//w  w w  .  ja  v a 2 s. c o m
 *
 * @return List of InputStream
 */
private static List<InputStream> prepareAnswer(Message message, String filename)
        throws IOException, MessagingException {
    Multipart multiPart = (Multipart) message.getContent();
    List<InputStream> input = new ArrayList<>();
    // For all multipart contents
    for (int i = 0; i < multiPart.getCount(); i++) {

        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
        String disp = part.getDisposition();
        String partName = part.getFileName();

        Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO, "is Multipart");
        // If multipart content is attachment
        if (!Part.ATTACHMENT.equalsIgnoreCase(disp) && !StringUtils.isNotBlank(partName)) {
            continue; // dealing with attachments only

        }

        if (Part.ATTACHMENT.equalsIgnoreCase(disp) || disp == null) {
            if (StringUtils.containsIgnoreCase(part.getFileName(), filename)) {
                Logger.getLogger(EMailManager.class.getName()).log(Level.INFO, "Attach found: {0}",
                        part.getFileName());
                final long start = System.currentTimeMillis();
                input.add(toInputStream(part));//add attach to answerlist
                final long answerDone = System.currentTimeMillis();
                Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO,
                        ">>Attach to inputstream: " + (answerDone - start) + " Millisek.");

            }
        }
    } //for multipart check
    return input;
}

From source file:com.email.ReceiveEmail.java

/**
 * Gather the email body/*from   w  w w . j a v  a 2  s.  c om*/
 *
 * @param p Part
 * @return String body
 */
private static String getEmailBodyText(Part p) {
    try {
        if (p.isMimeType("text/*")) {
            String s = (String) p.getContent();
            return s;
        }

        if (p.isMimeType("multipart/alternative")) {
            // prefer html text over plain text
            Multipart mp = (Multipart) p.getContent();
            String text = null;
            for (int i = 0; i < mp.getCount(); i++) {
                Part bp = mp.getBodyPart(i);
                if (bp.isMimeType("text/plain")) {
                    if (text == null) {
                        text = getEmailBodyText(bp);
                    }
                } else if (bp.isMimeType("text/html")) {
                    String s = getEmailBodyText(bp);
                    if (s != null) {
                        return s;
                    }
                } else {
                    return getEmailBodyText(bp);
                }
            }
            return text;
        } else if (p.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) p.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                String s = getEmailBodyText(mp.getBodyPart(i));
                if (s != null) {
                    return s;
                }
            }
        }
        return "";
    } catch (MessagingException | IOException ex) {
        ExceptionHandler.Handle(ex);
    }
    return "";
}

From source file:msgshow.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);/* w  w w . jav a2s  .c o  m*/

    /** Dump input stream .. 
            
    InputStream is = p.getInputStream();
    // If "is" is not already buffered, wrap a BufferedInputStream
    // around it.
    if (!(is instanceof BufferedInputStream))
        is = new BufferedInputStream(is);
    int c;
    while ((c = is.read()) != -1)
        System.out.write(c);
            
    **/

    String ct = p.getContentType();
    try {
        pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
        pr("BAD CONTENT-TYPE: " + ct);
    }
    String filename = p.getFileName();
    if (filename != null)
        pr("FILENAME: " + filename);

    /*
     * Using isMimeType to determine the content type avoids
     * fetching the actual content data until we need it.
     */
    if (p.isMimeType("text/plain")) {
        pr("This is plain text");
        pr("---------------------------");
        if (!showStructure && !saveAttachments)
            System.out.println((String) p.getContent());
    } else if (p.isMimeType("multipart/*")) {
        pr("This is a Multipart");
        pr("---------------------------");
        Multipart mp = (Multipart) p.getContent();
        level++;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
        level--;
    } else if (p.isMimeType("message/rfc822")) {
        pr("This is a Nested Message");
        pr("---------------------------");
        level++;
        dumpPart((Part) p.getContent());
        level--;
    } else {
        if (!showStructure && !saveAttachments) {
            /*
             * If we actually want to see the data, and it's not a
             * MIME type we know, fetch it and check its Java type.
             */
            Object o = p.getContent();
            if (o instanceof String) {
                pr("This is a string");
                pr("---------------------------");
                System.out.println((String) o);
            } else if (o instanceof InputStream) {
                pr("This is just an input stream");
                pr("---------------------------");
                InputStream is = (InputStream) o;
                int c;
                while ((c = is.read()) != -1)
                    System.out.write(c);
            } else {
                pr("This is an unknown type");
                pr("---------------------------");
                pr(o.toString());
            }
        } else {
            // just a separator
            pr("---------------------------");
        }
    }

    /*
     * If we're saving attachments, write out anything that
     * looks like an attachment into an appropriately named
     * file.  Don't overwrite existing files to prevent
     * mistakes.
     */
    if (saveAttachments && level != 0 && p instanceof MimeBodyPart && !p.isMimeType("multipart/*")) {
        String disp = p.getDisposition();
        // many mailers don't include a Content-Disposition
        if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
            if (filename == null)
                filename = "Attachment" + attnum++;
            pr("Saving attachment to file " + filename);
            try {
                File f = new File(filename);
                if (f.exists())
                    // XXX - could try a series of names
                    throw new IOException("file exists");
                ((MimeBodyPart) p).saveFile(f);
            } catch (IOException ex) {
                pr("Failed to save attachment: " + ex);
            }
            pr("---------------------------");
        }
    }
}

From source file:javamailclient.GmailAPI.java

/**
 * Return the primary text content of the message.
 *//* ww  w  .jav a  2s .co m*/
private static String getMessageBody(Part p) throws MessagingException, IOException {
    if (p.isMimeType("text/*")) {
        String s = (String) p.getContent();
        return s;
    }

    if (p.isMimeType("multipart/alternative")) {
        // prefer html text over plain text
        Multipart mp = (Multipart) p.getContent();
        String text = null;
        for (int i = 0; i < mp.getCount(); i++) {
            Part bp = mp.getBodyPart(i);
            if (bp.isMimeType("text/plain")) {
                if (text == null) {
                    text = getMessageBody(bp);
                }
                continue;
            } else if (bp.isMimeType("text/html")) {
                String s = getMessageBody(bp);
                if (s != null) {
                    return s;
                }
            } else {
                return getMessageBody(bp);
            }
        }
        return text;
    } else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            String s = getMessageBody(mp.getBodyPart(i));
            if (s != null) {
                return s;
            }
        }
    }

    return null;
}

From source file:mitm.common.security.smime.SMIMEUtils.java

/**
 * Split up the multipart in a message part and signed part. Returns null if the message
 * does not contain one of these parts or if it contains more or less than 2 parts.
 * @param multiPart//from   w  ww.j a  va2s . c om
 * @return first item is the message part, second the signature part
 * @throws MessagingException
 */
public static BodyPart[] dissectSigned(Multipart multipart) throws MessagingException {
    BodyPart messagePart = null;
    BodyPart signaturePart = null;

    if (multipart == null) {
        return null;
    }

    if (multipart.getCount() != 2) {
        logger.debug("Multipart does not contain 2 parts.");

        return null;
    }

    for (int i = 0; i < 2; i++) {
        BodyPart part = multipart.getBodyPart(i);

        /*
         * Check if we have found the signature part. We need to make sure that the content-type
         * is not multipart/signed because that fails when we have a clear signed message that
         * is signed again.
         */
        if (SMIMEHeader.getSMIMEContentType(part) == SMIMEHeader.Type.CLEAR_SIGNED
                && !part.isMimeType("multipart/signed")) {
            signaturePart = part;
        } else {
            messagePart = part;
        }
    }

    if (messagePart == null || signaturePart == null) {
        logger.debug("Multipart does not contain a message and signature part.");

        return null;
    }

    return new BodyPart[] { messagePart, signaturePart };
}

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  w  w.j  av  a2s  .  c o m
    }
}

From source file:MainClass.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);//from  w w w .  ja  v  a2 s  .  co m

    /**
     * Dump input stream ..
     * 
     * InputStream is = p.getInputStream(); // If "is" is not already buffered,
     * wrap a BufferedInputStream // around it. if (!(is instanceof
     * BufferedInputStream)) is = new BufferedInputStream(is); int c; while ((c =
     * is.read()) != -1) System.out.write(c);
     * 
     */

    String ct = p.getContentType();
    try {
        pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
        pr("BAD CONTENT-TYPE: " + ct);
    }
    String filename = p.getFileName();
    if (filename != null)
        pr("FILENAME: " + filename);

    /*
     * Using isMimeType to determine the content type avoids fetching the actual
     * content data until we need it.
     */
    if (p.isMimeType("text/plain")) {
        pr("This is plain text");
        pr("---------------------------");
        if (!showStructure && !saveAttachments)
            System.out.println((String) p.getContent());
    } else if (p.isMimeType("multipart/*")) {
        pr("This is a Multipart");
        pr("---------------------------");
        Multipart mp = (Multipart) p.getContent();
        level++;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
        level--;
    } else if (p.isMimeType("message/rfc822")) {
        pr("This is a Nested Message");
        pr("---------------------------");
        level++;
        dumpPart((Part) p.getContent());
        level--;
    } else {
        if (!showStructure && !saveAttachments) {
            /*
             * If we actually want to see the data, and it's not a MIME type we
             * know, fetch it and check its Java type.
             */
            Object o = p.getContent();
            if (o instanceof String) {
                pr("This is a string");
                pr("---------------------------");
                System.out.println((String) o);
            } else if (o instanceof InputStream) {
                pr("This is just an input stream");
                pr("---------------------------");
                InputStream is = (InputStream) o;
                int c;
                while ((c = is.read()) != -1)
                    System.out.write(c);
            } else {
                pr("This is an unknown type");
                pr("---------------------------");
                pr(o.toString());
            }
        } else {
            // just a separator
            pr("---------------------------");
        }
    }

    /*
     * If we're saving attachments, write out anything that looks like an
     * attachment into an appropriately named file. Don't overwrite existing
     * files to prevent mistakes.
     */
    if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) {
        String disp = p.getDisposition();
        // many mailers don't include a Content-Disposition
        if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
            if (filename == null)
                filename = "Attachment" + attnum++;
            pr("Saving attachment to file " + filename);
            try {
                File f = new File(filename);
                if (f.exists())
                    // XXX - could try a series of names
                    throw new IOException("file exists");
                ((MimeBodyPart) p).saveFile(f);
            } catch (IOException ex) {
                pr("Failed to save attachment: " + ex);
            }
            pr("---------------------------");
        }
    }
}

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()));
                }// w  ww.java2  s  .  c o  m
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        saveAttachment((Part) part.getContent(), destDir);
    }
}