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:com.aurel.track.util.emailHandling.MailReader.java

private static String hadleMultipartAlternative(Part part, List<EmailAttachment> attachments,
        boolean ignoreAttachments) throws IOException, MessagingException {
    LOGGER.debug("hadleMultipartAlternative");
    // prefer HTML text over plain text
    Multipart mp = (Multipart) part.getContent();
    String plainText = null;/*from   w w  w. j  a  v  a2 s . c o  m*/
    String otherText = null;
    for (int i = 0; i < mp.getCount(); i++) {
        Part bp = mp.getBodyPart(i);
        if (bp.isMimeType("text/html")) {
            return getText(bp);
        } else if (bp.isMimeType("text/plain")) {
            plainText = getText(bp);
        } else {
            LOGGER.debug("Process alternative body part having mimeType:" + bp.getContentType());
            otherText = handlePart(bp, attachments, ignoreAttachments).toString();
        }
    }
    if (otherText != null) {
        return otherText;
    } else {
        return plainText;
    }
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param dataSource - The email message
 * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise
 * @param authList - If authRequired is true, this must be populated with the auth info
 * @return List - The list of email messages in the mailstore
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing
 *//*from   w ww.  j av a2  s.  c  o m*/
public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource,
        final boolean authRequired, final List<String> authList) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("dataSource: {}", dataSource);
        DEBUGGER.debug("authRequired: {}", authRequired);
        DEBUGGER.debug("authList: {}", authList);
    }

    Folder mailFolder = null;
    Session mailSession = null;
    Folder archiveFolder = null;
    List<EmailMessage> emailMessages = null;

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -24);

    final Long TIME_PERIOD = cal.getTimeInMillis();
    final URLName URL_NAME = (authRequired)
            ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1))
            : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, null, null);

    if (DEBUG) {
        DEBUGGER.debug("timePeriod: {}", TIME_PERIOD);
        DEBUGGER.debug("URL_NAME: {}", URL_NAME);
    }

    try {
        // Set up mail session
        mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator())
                : Session.getDefaultInstance(dataSource);

        if (DEBUG) {
            DEBUGGER.debug("mailSession: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        Store mailStore = mailSession.getStore(URL_NAME);
        mailStore.connect();

        if (DEBUG) {
            DEBUGGER.debug("mailStore: {}", mailStore);
        }

        if (!(mailStore.isConnected())) {
            throw new MessagingException("Failed to connect to mail service. Cannot continue.");
        }

        mailFolder = mailStore.getFolder("inbox");
        archiveFolder = mailStore.getFolder("archive");

        if (!(mailFolder.exists())) {
            throw new MessagingException("Requested folder does not exist. Cannot continue.");
        }

        mailFolder.open(Folder.READ_WRITE);

        if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) {
            throw new MessagingException("Failed to open requested folder. Cannot continue");
        }

        if (!(archiveFolder.exists())) {
            archiveFolder.create(Folder.HOLDS_MESSAGES);
        }

        Message[] mailMessages = mailFolder.getMessages();

        if (mailMessages.length == 0) {
            throw new MessagingException("No messages were found in the provided store.");
        }

        emailMessages = new ArrayList<EmailMessage>();

        for (Message message : mailMessages) {
            if (DEBUG) {
                DEBUGGER.debug("MailMessage: {}", message);
            }

            // validate the message here
            String messageId = message.getHeader("Message-ID")[0];
            Long messageDate = message.getReceivedDate().getTime();

            if (DEBUG) {
                DEBUGGER.debug("messageId: {}", messageId);
                DEBUGGER.debug("messageDate: {}", messageDate);
            }

            // only get emails for the last 24 hours
            // this should prevent us from pulling too
            // many emails
            if (messageDate >= TIME_PERIOD) {
                // process it
                Multipart attachment = (Multipart) message.getContent();
                Map<String, InputStream> attachmentList = new HashMap<String, InputStream>();

                for (int x = 0; x < attachment.getCount(); x++) {
                    BodyPart bodyPart = attachment.getBodyPart(x);

                    if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) {
                        continue;
                    }

                    attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream());
                }

                List<String> toList = new ArrayList<String>();
                List<String> ccList = new ArrayList<String>();
                List<String> bccList = new ArrayList<String>();
                List<String> fromList = new ArrayList<String>();

                for (Address from : message.getFrom()) {
                    fromList.add(from.toString());
                }

                if ((message.getRecipients(RecipientType.TO) != null)
                        && (message.getRecipients(RecipientType.TO).length != 0)) {
                    for (Address to : message.getRecipients(RecipientType.TO)) {
                        toList.add(to.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.CC) != null)
                        && (message.getRecipients(RecipientType.CC).length != 0)) {
                    for (Address cc : message.getRecipients(RecipientType.CC)) {
                        ccList.add(cc.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.BCC) != null)
                        && (message.getRecipients(RecipientType.BCC).length != 0)) {
                    for (Address bcc : message.getRecipients(RecipientType.BCC)) {
                        bccList.add(bcc.toString());
                    }
                }

                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setMessageTo(toList);
                emailMessage.setMessageCC(ccList);
                emailMessage.setMessageBCC(bccList);
                emailMessage.setEmailAddr(fromList);
                emailMessage.setMessageAttachments(attachmentList);
                emailMessage.setMessageDate(message.getSentDate());
                emailMessage.setMessageSubject(message.getSubject());
                emailMessage.setMessageBody(message.getContent().toString());
                emailMessage.setMessageSources(message.getHeader("Received"));

                if (DEBUG) {
                    DEBUGGER.debug("emailMessage: {}", emailMessage);
                }

                emailMessages.add(emailMessage);

                if (DEBUG) {
                    DEBUGGER.debug("emailMessages: {}", emailMessages);
                }
            }

            // archive it
            archiveFolder.open(Folder.READ_WRITE);

            if (archiveFolder.isOpen()) {
                mailFolder.copyMessages(new Message[] { message }, archiveFolder);
                message.setFlag(Flags.Flag.DELETED, true);
            }
        }
    } catch (IOException iox) {
        throw new MessagingException(iox.getMessage(), iox);
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } finally {
        try {
            if ((mailFolder != null) && (mailFolder.isOpen())) {
                mailFolder.close(true);
            }

            if ((archiveFolder != null) && (archiveFolder.isOpen())) {
                archiveFolder.close(false);
            }
        } catch (MessagingException mx) {
            ERROR_RECORDER.error(mx.getMessage(), mx);
        }
    }

    return emailMessages;
}

From source file:mx.uaq.facturacion.enlace.EmailParserUtils.java

/**
 * Parses any {@link Multipart} instances that contain text or Html attachments,
 * {@link InputStream} instances, additional instances of {@link Multipart}
 * or other attached instances of {@link javax.mail.Message}.
 *
 * Will create the respective {@link EmailFragment}s representing those attachments.
 *
 * Instances of {@link javax.mail.Message} are delegated to
 * {@link #handleMessage(File, javax.mail.Message, List)}. Further instances
 * of {@link Multipart} are delegated to
 * {@link #handleMultipart(File, Multipart, javax.mail.Message, List)}.
 *
 * @param directory Must not be null//from  w  w  w  . j  a v  a 2 s  .c o  m
 * @param multipart Must not be null
 * @param mailMessage Must not be null
 * @param emailFragments Must not be null
 */
public static void handleMultipart(File directory, Multipart multipart, javax.mail.Message mailMessage,
        List<EmailFragment> emailFragments) {

    Assert.notNull(directory, "The directory must not be null.");
    Assert.notNull(multipart, "The multipart object to be parsed must not be null.");
    Assert.notNull(mailMessage, "The mail message to be parsed must not be null.");
    Assert.notNull(emailFragments, "The collection of emailfragments must not be null.");

    final int count;

    try {
        count = multipart.getCount();

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(String.format("Number of enclosed BodyPart objects: %s.", count));
        }

    } catch (MessagingException e) {
        throw new IllegalStateException("Error while retrieving the number of enclosed BodyPart objects.", e);
    }

    for (int i = 0; i < count; i++) {

        final BodyPart bp;

        try {
            bp = multipart.getBodyPart(i);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving body part.", e);
        }

        final String contentType;
        String filename;
        final String disposition;
        final String subject;

        try {

            contentType = bp.getContentType();
            filename = bp.getFileName();
            disposition = bp.getDisposition();
            subject = mailMessage.getSubject();

            if (filename == null && bp instanceof MimeBodyPart) {
                filename = ((MimeBodyPart) bp).getContentID();
            }

        } catch (MessagingException e) {
            throw new IllegalStateException("Unable to retrieve body part meta data.", e);
        }

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(String.format(
                    "BodyPart - Content Type: '%s', filename: '%s', disposition: '%s', subject: '%s'",
                    new Object[] { contentType, filename, disposition, subject }));
        }

        if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
            LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType));
        }

        final Object content;

        try {
            content = bp.getContent();
        } catch (IOException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        }

        if (content instanceof String) {

            if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
                emailFragments.add(new EmailFragment(directory, i + "-" + filename, content));
                LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType));
            } else {

                final String textFilename;
                final ContentType ct;

                try {
                    ct = new ContentType(contentType);
                } catch (ParseException e) {
                    throw new IllegalStateException("Error while parsing content type '" + contentType + "'.",
                            e);
                }

                if ("text/plain".equalsIgnoreCase(ct.getBaseType())) {
                    textFilename = "message.txt";
                } else if ("text/html".equalsIgnoreCase(ct.getBaseType())) {
                    textFilename = "message.html";
                } else {
                    textFilename = "message.other";
                }

                emailFragments.add(new EmailFragment(directory, textFilename, content));
            }

        } else if (content instanceof InputStream) {

            final InputStream inputStream = (InputStream) content;
            final ByteArrayOutputStream bis = new ByteArrayOutputStream();

            try {
                IOUtils.copy(inputStream, bis);
            } catch (IOException e) {
                throw new IllegalStateException(
                        "Error while copying input stream to the ByteArrayOutputStream.", e);
            }

            emailFragments.add(new EmailFragment(directory, filename, bis.toByteArray()));

        } else if (content instanceof javax.mail.Message) {
            handleMessage(directory, (javax.mail.Message) content, emailFragments);
        } else if (content instanceof Multipart) {
            final Multipart mp2 = (Multipart) content;
            handleMultipart(directory, mp2, mailMessage, emailFragments);
        } else {
            throw new IllegalStateException("Content type not handled: " + content.getClass().getSimpleName());
        }
    }
}

From source file:de.saly.elasticsearch.support.IndexableMailMessage.java

private static String getText(final Part p, int depth) throws MessagingException, IOException {

    if (depth >= 100) {
        throw new IOException("Endless recursion detected ");
    }//ww w  .j  a  v  a2s  .c o m

    // TODO fix encoding for buggy encoding headers

    if (p.isMimeType("text/*")) {

        Object content = null;
        try {
            content = p.getContent();
        } catch (final Exception e) {
            logger.error("Unable to index the content of a message due to {}", e.toString());
            return null;
        }

        if (content instanceof String) {
            final String s = (String) p.getContent();
            return s;

        }

        if (content instanceof InputStream) {

            final InputStream in = (InputStream) content;
            // TODO guess encoding with
            // http://code.google.com/p/juniversalchardet/
            final String s = IOUtils.toString(in, "UTF-8");
            IOUtils.closeQuietly(in);
            return s;

        }

        throw new MessagingException("Unknown content class representation: " + content.getClass());

    }

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

    return null;
}

From source file:de.saly.elasticsearch.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withAttachments, final boolean stripTags, List<String> headersToFields)
        throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }//  www. j a v a2s .  com

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}

From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java

private static String getText(final Part p, int depth, final boolean preferHtmlContent)
        throws MessagingException, IOException {

    if (depth >= 100) {
        throw new IOException("Endless recursion detected ");
    }/*ww w  .j  a  v a  2  s. co  m*/

    // TODO fix encoding for buggy encoding headers

    if (p.isMimeType("text/*")) {

        Object content = null;
        try {
            content = p.getContent();
        } catch (final Exception e) {
            logger.error("Unable to index the content of a message due to {}", e.toString());
            return null;
        }

        if (content instanceof String) {
            final String s = (String) p.getContent();
            return s;

        }

        if (content instanceof InputStream) {

            final InputStream in = (InputStream) content;
            // TODO guess encoding with
            // http://code.google.com/p/juniversalchardet/
            final String s = IOUtils.toString(in, "UTF-8");
            IOUtils.closeQuietly(in);
            return s;

        }

        throw new MessagingException("Unknown content class representation: " + content.getClass());

    }

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

    return null;
}

From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withHtmlContent, final boolean preferHtmlContent, final boolean withAttachments,
        final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }/*from  ww  w . j  av a2 s. c o m*/

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0, preferHtmlContent);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withHtmlContent) {

        // try {

        String htmlContent = getText(jmm, 0, true);

        im.setHtmlContent(htmlContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}

From source file:org.apache.james.transport.mailets.ICSSanitizerTest.java

@Test
void validTextCalendarShouldNotBeSanitized() throws Exception {
    FakeMail mail = FakeMail.builder()//w  w  w.  j a  v  a 2  s .c  o  m
            .mimeMessage(MimeMessageBuilder.mimeMessageBuilder()
                    .setMultipartWithBodyParts(MimeMessageBuilder.bodyPartBuilder().type("text/calendar")
                            .data("Not empty").addHeader("X-CUSTOM",
                                    "Because it is a valid ICS it should not be pushed in body")))
            .build();

    testee.service(mail);

    Object content = mail.getMessage().getContent();

    assertThat(content).isInstanceOf(Multipart.class);
    Multipart multipart = (Multipart) content;
    assertThat(multipart.getCount()).isEqualTo(1);

    SharedByteArrayInputStream inputStream = (SharedByteArrayInputStream) multipart.getBodyPart(0).getContent();
    assertThat(IOUtils.toString(inputStream, StandardCharsets.UTF_8)).doesNotContain("X-CUSTOM");
}

From source file:org.apache.james.transport.mailets.ICSSanitizerTest.java

@Test
void serviceShouldEnhanceTextCalendarOnlyHeaders() throws Exception {
    FakeMail mail = FakeMail.builder().mimeMessage(MimeMessageUtil
            .mimeMessageFromStream(ClassLoaderUtils.getSystemResourceAsSharedStream("ics_in_header.eml")))
            .build();//from ww  w  . j  av  a2s.  c  om

    testee.service(mail);

    Object content = mail.getMessage().getContent();

    assertThat(content).isInstanceOf(Multipart.class);
    Multipart multipart = (Multipart) content;
    assertThat(multipart.getCount()).isEqualTo(1);

    assertThat(multipart.getBodyPart(0).getContent()).isEqualTo("BEGIN: VCALENDAR\r\n"
            + "PRODID: -//Mozilla.org/NONSGML Mozilla Calendar V1.1//EN\r\n" + "VERSION: 2.0\r\n"
            + "METHOD: REPLY\r\n" + "BEGIN: VEVENT\r\n" + "CREATED: 20180911T144134Z\r\n"
            + "LAST-MODIFIED: 20180912T085818Z\r\n" + "DTSTAMP: 20180912T085818Z\r\n"
            + "UID: f1514f44bf39311568d64072945fc3b2973debebb0d550e8c841f3f0604b2481e047fe\r\n"
            + " b2aab16e43439a608f28671ab7c10e754cbbe63441a01ba232a553df751eb0931728d67672\r\n" + " \r\n"
            + "SUMMARY: Point Produit\r\n" + "PRIORITY: 5\r\n"
            + "ORGANIZER;CN=Bob;X-OBM-ID=348: mailto:bob@linagora.com\r\n"
            + "ATTENDEE;CN=Alice;PARTSTAT=ACCEPTED;CUTYPE=INDIVIDUAL;X-OBM-ID=810: mailto:alice@linagora.com\r\n"
            + "DTSTART: 20180919T123000Z\r\n" + "DURATION: PT1H\r\n" + "TRANSP: OPAQUE\r\n" + "SEQUENCE: 0\r\n"
            + "X-LIC-ERROR;X-LIC-ERRORTYPE=VALUE-PARSE-ERROR: No value for X property. Rem\r\n"
            + " oving entire property:\r\n" + "CLASS: PUBLIC\r\n" + "X-OBM-DOMAIN: linagora.com\r\n"
            + "X-OBM-DOMAIN-UUID: 02874f7c-d10e-102f-acda-0015176f7922\r\n"
            + "LOCATION: T\u0083l\u0083phone\r\n" + "END: VEVENT\r\n" + "END: VCALENDAR\r\n"
            + "Content-class: urn:content-classes:calendarmessage\r\n"
            + "Content-type: text/calendar; method=REPLY; charset=UTF-8\r\n"
            + "Content-transfer-encoding: 8BIT\r\n" + "Content-Disposition: attachment");
    assertThat(multipart.getBodyPart(0).getContentType())
            .startsWith("text/calendar; method=REPLY; charset=UTF-8");
}

From source file:org.apereo.portal.portlets.account.EmailPasswordResetNotificationImplTest.java

private String getBodyHtml(Multipart msg) throws Exception {
    for (int i = 0; i < msg.getCount(); i++) {
        BodyPart part = msg.getBodyPart(i);
        String type = part.getContentType();

        if ("text/plain".equals(type) || "text/html".equals(type)) {
            DataHandler handler = part.getDataHandler();
            String val = IOUtils.toString(handler.getInputStream());
            return val;
        }/*from   w ww.j av a 2 s . c o  m*/
    }

    return null;
}