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:com.intranet.intr.inbox.EmpControllerInbox.java

private static correoNoLeidos analizaParteDeMensaje2(correoNoLeidos correo, List<String> arc, List<String> rar,
        Part unaParte) {//from  w  w w .j a  va2  s.c  om
    String r = null;
    try {
        System.out.println("CORREO NUM: ");
        // Si es multipart, se analiza cada una de sus partes recursivamente.
        if (unaParte.isMimeType("multipart/*")) {
            Multipart multi;
            multi = (Multipart) unaParte.getContent();
            System.out.println("for MULTIPART");
            for (int j = 0; j < multi.getCount(); j++) {
                System.out.println("Si es multi");
                analizaParteDeMensaje2(correo, arc, rar, multi.getBodyPart(j));
            }
        } else {
            // Si es texto, se escribe el texto.
            if (unaParte.isMimeType("text/*")) {
                System.out.println("Texto " + unaParte.getContentType());
                System.out.println(unaParte.getContent());
                System.out.println("---------------------------------");
                correo.setContenido((String) unaParte.getContent());
            }

            // Si es imagen, se guarda en fichero y se visualiza en JFrame
            if (unaParte.isMimeType("image/*")) {
                System.out.println("IMAGEN SYSTEM");
                System.out.println("Imagen " + unaParte.getContentType());
                System.out.println("Fichero=" + unaParte.getFileName());
                System.out.println("---------------------------------");

                arc.add("/Intranet/resources/archivosMail/verCorreo/" + salvaImagenEnFichero(unaParte));
                //visualizaImagenEnJFrame(unaParte);
            } else {
                System.out.println("ELSE img");
                // Si no es ninguna de las anteriores, se escribe en pantalla
                // el tipo.
                System.out.println("Recibido " + unaParte.getContentType());
                System.out.println("---------------------------------");
                if (salvaImagenEnFichero(unaParte) != null & salvaImagenEnFichero(unaParte) != "") {
                    rar.add(salvaImagenEnFichero(unaParte));
                }
                correo.setContenido((String) unaParte.getContent());
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    correo.setImagenes(arc);
    correo.setRar(rar);
    return correo;
}

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 w  w .j  a va  2 s  .co  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: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 ");
    }//from w  w  w  .j  av a 2 s  .  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.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 ");
    }/* w w  w .jav a2 s.  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, 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.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()));
    }/*w  w  w.  j a  v 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);

        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

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

    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:com.angstoverseer.service.mail.MailServiceImpl.java

@Override
public void handleIncomingEmail(InputStream inputStream) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {/* www  . ja v  a 2 s  .c  o m*/
        MimeMessage mimeMessage = new MimeMessage(session, inputStream);

        Object messageContent = mimeMessage.getContent();
        String message;
        if (messageContent instanceof Multipart) {
            Multipart mp = (Multipart) messageContent;
            BodyPart bodyPart = mp.getBodyPart(0);
            InputStream is = bodyPart.getInputStream();
            message = convertStreamToString(is);
        } else {
            message = (String) messageContent;
        }

        Address sender = mimeMessage.getFrom()[0];
        final String commandOutput = commandService.process(message, extractEmail(sender.toString()));

        sendResponseMail(sender, commandOutput, mimeMessage.getSubject());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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();/*  w ww. jav a 2  s  .  co  m*/

    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  w w. j a  v a2 s . com*/
    }

    return null;
}

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

@Test
void validTextCalendarShouldNotBeSanitized() throws Exception {
    FakeMail mail = FakeMail.builder()/*from ww  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");
}