Example usage for javax.mail Multipart getCount

List of usage examples for javax.mail Multipart getCount

Introduction

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

Prototype

public synchronized int getCount() throws MessagingException 

Source Link

Document

Return the number of enclosed BodyPart objects.

Usage

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

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

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

    try {//from   w w  w.  java 2s  .com

        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:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java

public static Body getMessageBody(MimeMessage message, String mimeType) {
    try {//from  w  w  w .  j a v a  2s  . com

        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:org.jevis.emaildatasource.EMailManager.java

/**
 * Find attachment and save it in inputstream
 *
 * @param message EMail message/* www.  j a v a  2  s .c om*/
 *
 * @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:msgshow.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);//from  w  ww.j  a  v a 2 s  .  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: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  www. j a va2  s  .  c  om
    }
}

From source file:com.email.ReceiveEmail.java

/**
 * Gather the email body/*from  w ww .j ava2 s. co m*/
 *
 * @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: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 .  j  a  va  2s. 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: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()));
                }/*from w w w.  ja v a  2s.com*/
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        saveAttachment((Part) part.getContent(), destDir);
    }
}

From source file:com.cubusmail.mail.text.MessageTextUtil.java

/**
 * @param part//from   w w w .j  a v  a2s. c  om
 * @param messageHandler
 * @param loadImages
 * @param reply
 * @throws MessagingException
 * @throws IOException
 */
public static void messageTextFromPart(Part part, MessageHandler messageHandler, boolean loadImages,
        MessageTextMode mode, Preferences preferences, int level) throws MessagingException, IOException {

    log.debug("Content type of part: " + part.getContentType());

    if (mode == MessageTextMode.DISPLAY || mode == MessageTextMode.DRAFT) {
        if (MessageUtils.isImagepart(part)) {
            messageHandler.setMessageImageHtml(createImageMessageText(messageHandler.getId()));
        } else if (!preferences.isShowHtml() && !StringUtils.isEmpty(messageHandler.getMessageTextPlain())) {
            return;
        } else if (preferences.isShowHtml() && !StringUtils.isEmpty(messageHandler.getMessageTextHtml())) {
            return;
        } else if (part.isMimeType("text/plain")) {
            String text = readPart(part);
            if (!StringUtils.isBlank(text)) {
                messageHandler.setMessageTextPlain(formatPlainText(text, mode));
            }
        } else if (part.isMimeType("text/html")) {
            if (preferences.isShowHtml()) {
                String text = readPart(part);
                boolean[] hasImages = new boolean[] { false };
                if (!StringUtils.isBlank(convertHtml2PlainText(text))) {
                    text = formatHTMLText(text, loadImages, hasImages);
                    messageHandler.setMessageTextHtml(text);
                    messageHandler.setHtmlMessage(true);
                    messageHandler.setHasImages(hasImages[0]);
                }
            } else {
                // only if there is no plain text part found
                if (StringUtils.isEmpty(messageHandler.getMessageTextPlain())) {
                    String text = readPart(part);
                    text = convertHtml2PlainText(text);
                    if (!StringUtils.isBlank(text)) {
                        text = formatPlainText(text, mode);
                        messageHandler.setMessageTextPlain(text);
                    }
                }
            }
        } else if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                Part subPart = mp.getBodyPart(i);
                messageTextFromPart(subPart, messageHandler, loadImages, mode, preferences, level++);
            }
        }
    } else if (mode == MessageTextMode.REPLY) {
        if (!preferences.isCreateHtmlMsgs() && !StringUtils.isEmpty(messageHandler.getMessageTextPlain())) {
            return;
        } else if (preferences.isCreateHtmlMsgs()
                && !StringUtils.isEmpty(messageHandler.getMessageTextHtml())) {
            return;
        } else if (part.isMimeType("text/plain")) {
            String text = readPart(part);
            text = quotePlainText(text);
            if (preferences.isCreateHtmlMsgs()) {
                text = convertPlainText2Html(text, mode);
                messageHandler.setMessageTextHtml(text);
                messageHandler.setHtmlMessage(true);
            } else {
                messageHandler.setMessageTextPlain(text);
            }
        } else if (part.isMimeType("text/html") && StringUtils.isEmpty(messageHandler.getMessageTextPlain())) {
            String text = readPart(part);
            text = convertHtml2PlainText(text);
            text = quotePlainText(text);
            if (preferences.isCreateHtmlMsgs()) {
                text = convertPlainText2Html(text, mode);
                messageHandler.setMessageTextHtml(text);
                messageHandler.setHtmlMessage(true);
            } else {
                messageHandler.setMessageTextPlain(text);
            }
        } else if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                Part subPart = mp.getBodyPart(i);
                messageTextFromPart(subPart, messageHandler, loadImages, mode, preferences, level++);
            }
        }
    }
}

From source file:MainClass.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);/*from   w  ww  .j av  a 2  s.  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.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("---------------------------");
        }
    }
}