Example usage for javax.mail.internet MimeBodyPart MimeBodyPart

List of usage examples for javax.mail.internet MimeBodyPart MimeBodyPart

Introduction

In this page you can find the example usage for javax.mail.internet MimeBodyPart MimeBodyPart.

Prototype

public MimeBodyPart(InputStream is) throws MessagingException 

Source Link

Document

Constructs a MimeBodyPart by reading and parsing the data from the specified input stream.

Usage

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

public static MimeBodyPart makeContentBodyPartRaw(MimeBodyPart sourceMessage, HeaderMatcher matcher)
        throws IOException, MessagingException {
    /*/*w  w  w .ja v  a 2s .  co m*/
     * getRawInputStream() can throw a MessagingException when the source message is a MimeMessage
     * that is created in code (ie. not from a stream)
     */
    InputStream messageStream = sourceMessage.getRawInputStream();

    MimeBodyPart newBodyPart = new MimeBodyPart(messageStream);

    HeaderUtils.copyHeaders(sourceMessage, newBodyPart, matcher);

    return newBodyPart;
}

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

public static MimeBodyPart makeContentBodyPartRaw(MimeMessage sourceMessage, HeaderMatcher matcher)
        throws IOException, MessagingException {
    /*/*from w w  w.j  a v  a 2  s  . com*/
     * getRawInputStream() can throw a MessagingException when the source message is a MimeMessage
     * that is created in code (ie. not from a stream)
     */
    InputStream messageStream = sourceMessage.getRawInputStream();

    MimeBodyPart newBodyPart = new MimeBodyPart(messageStream);

    HeaderUtils.copyHeaders(sourceMessage, newBodyPart, matcher);

    return newBodyPart;
}

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

private Optional<byte[]> extractContent(Object rawMime) throws MessagingException {
    try {//from ww  w . j  av  a 2 s  .  c  o  m
        MimeBodyPart mimeBodyPart = new MimeBodyPart(new ByteArrayInputStream((byte[]) rawMime));
        return Optional.fromNullable(IOUtils.toByteArray(mimeBodyPart.getInputStream()));
    } catch (IOException e) {
        log("Error while extracting content from mime part", e);
        return Optional.absent();
    } catch (ClassCastException e) {
        log("Invalid map attribute types.", e);
        return Optional.absent();
    }
}

From source file:com.silverpeas.mailinglist.service.job.TestMessageCheckerWithStubs.java

@Test
public void testCheckNewMessages() throws MessagingException, IOException {
    org.jvnet.mock_javamail.Mailbox.clearAll();
    MessageChecker messageChecker = getMessageChecker();
    messageChecker.removeListener("componentId");
    messageChecker.removeListener("thesimpsons@silverpeas.com");
    messageChecker.removeListener("theflanders@silverpeas.com");
    StubMessageListener mockListener1 = new StubMessageListener("thesimpsons@silverpeas.com");
    StubMessageListener mockListener2 = new StubMessageListener("theflanders@silverpeas.com");
    messageChecker.addMessageListener(mockListener1);
    messageChecker.addMessageListener(mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Plain text Email test with attachment");
    MimeBodyPart attachment = new MimeBodyPart(
            TestMessageCheckerWithStubs.class.getResourceAsStream("lemonde.html"));
    attachment.setDisposition(Part.INLINE);
    attachment.setFileName("lemonde.html");
    MimeBodyPart body = new MimeBodyPart();
    body.setText(textEmailContent);//ww w  .j  a  va 2  s.  com
    Multipart multiPart = new MimeMultipart();
    multiPart.addBodyPart(body);
    multiPart.addBodyPart(attachment);
    mail.setContent(multiPart);
    mail.setSentDate(new Date());
    Date sentDate1 = new Date(mail.getSentDate().getTime());
    Transport.send(mail);

    mail = new MimeMessage(messageChecker.getMailSession());
    bart = new InternetAddress("bart.simpson@silverpeas.com");
    theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Plain text Email test");
    mail.setText(textEmailContent);
    mail.setSentDate(new Date());
    Date sentDate2 = new Date(mail.getSentDate().getTime());
    Transport.send(mail);

    //Unauthorized email
    mail = new MimeMessage(messageChecker.getMailSession());
    bart = new InternetAddress("marge.simpson@silverpeas.com");
    theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Plain text Email test");
    mail.setText(textEmailContent);
    mail.setSentDate(new Date());
    Transport.send(mail);

    assertThat(org.jvnet.mock_javamail.Mailbox.get("thesimpsons@silverpeas.com").size(), is(3));

    messageChecker.checkNewMessages(new Date());
    assertThat(mockListener2.getMessageEvent(), is(nullValue()));
    MessageEvent event = mockListener1.getMessageEvent();
    assertThat(event, is(notNullValue()));
    assertThat(event.getMessages(), is(notNullValue()));
    assertThat(event.getMessages(), hasSize(2));
    Message message = event.getMessages().get(0);
    assertThat(message.getSender(), is("bart.simpson@silverpeas.com"));
    assertThat(message.getTitle(), is("Plain text Email test with attachment"));
    assertThat(message.getBody(), is(textEmailContent));
    assertThat(message.getSummary(), is(textEmailContent.substring(0, 200)));
    assertThat(message.getSentDate().getTime(), is(sentDate1.getTime()));
    assertThat(message.getAttachmentsSize(), greaterThan(0L));
    assertThat(message.getAttachments(), hasSize(1));
    String path = MessageFormat.format(theSimpsonsAttachmentPath,
            new Object[] { messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()) });
    Attachment attached = message.getAttachments().iterator().next();
    assertThat(attached.getPath(), is(path));
    assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com"));

    message = event.getMessages().get(1);
    assertThat(message.getSender(), is("bart.simpson@silverpeas.com"));
    assertThat(message.getTitle(), is("Plain text Email test"));
    assertThat(message.getBody(), is(textEmailContent));
    assertThat(message.getSummary(), is(textEmailContent.substring(0, 200)));
    assertThat(message.getAttachmentsSize(), is(0L));
    assertThat(message.getAttachments(), hasSize(0));
    assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com"));
    assertThat(message.getSentDate().getTime(), is(sentDate2.getTime()));
}

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

private byte[] extractContent(byte[] rawMime) throws IOException {
    try {/*  w ww .j  a v  a2 s  . c om*/
        MimeBodyPart mimeBodyPart = new MimeBodyPart(new ByteArrayInputStream(rawMime));
        return IOUtils.toByteArray(mimeBodyPart.getInputStream());
    } catch (MessagingException e) {
        throw new IOException(e);
    }
}

From source file:org.apache.olingo.fit.V3Services.java

@Override
public InputStream exploreMultipart(final List<Attachment> attachments, final String boundary,
        final boolean contineOnError) throws IOException {

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    Response res = null;/*from   w w w .j  a  va  2 s .co m*/
    boolean goon = true;
    for (int i = 0; i < attachments.size() && goon; i++) {
        try {
            final Attachment obj = attachments.get(i);
            bos.write(("--" + boundary).getBytes());
            bos.write(Constants.CRLF);

            final Object content = obj.getDataHandler().getContent();
            if (content instanceof MimeMultipart) {
                final Map<String, String> references = new HashMap<String, String>();

                final String cboundary = "changeset_" + UUID.randomUUID().toString();
                bos.write(("Content-Type: multipart/mixed;boundary=" + cboundary).getBytes());
                bos.write(Constants.CRLF);
                bos.write(Constants.CRLF);

                final ByteArrayOutputStream chbos = new ByteArrayOutputStream();
                String lastContebtID = null;
                try {
                    for (int j = 0; j < ((MimeMultipart) content).getCount(); j++) {
                        final MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) content).getBodyPart(j);
                        lastContebtID = part.getContentID();
                        addChangesetItemIntro(chbos, lastContebtID, cboundary);

                        res = bodyPartRequest(new MimeBodyPart(part.getInputStream()), references);
                        if (res == null || res.getStatus() >= 400) {
                            throw new Exception("Failure processing changeset");
                        }

                        addSingleBatchResponse(res, lastContebtID, chbos);
                        references.put("$" + lastContebtID, res.getHeaderString("Location"));
                    }

                    bos.write(chbos.toByteArray());
                    IOUtils.closeQuietly(chbos);

                    bos.write(("--" + cboundary + "--").getBytes());
                    bos.write(Constants.CRLF);
                } catch (Exception e) {
                    LOG.warn("While processing changeset", e);
                    IOUtils.closeQuietly(chbos);

                    addChangesetItemIntro(bos, lastContebtID, cboundary);

                    if (res == null || res.getStatus() < 400) {
                        addErrorBatchResponse(e, "1", bos);
                    } else {
                        addSingleBatchResponse(res, lastContebtID, bos);
                    }

                    goon = contineOnError;
                }
            } else {
                addItemIntro(bos);

                res = bodyPartRequest(new MimeBodyPart(obj.getDataHandler().getInputStream()));

                if (res.getStatus() >= 400) {
                    goon = contineOnError;
                    throw new Exception("Failure processing changeset");
                }

                addSingleBatchResponse(res, bos);
            }
        } catch (Exception e) {
            if (res == null || res.getStatus() < 400) {
                addErrorBatchResponse(e, bos);
            } else {
                addSingleBatchResponse(res, bos);
            }
        }
    }

    bos.write(("--" + boundary + "--").getBytes());

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:org.apache.james.core.builder.MimeMessageBuilder.java

public static BodyPart bodyPartFromBytes(byte[] bytes) throws MessagingException {
    return new MimeBodyPart(new ByteArrayInputStream(bytes));
}

From source file:com.stimulus.archiva.extraction.MessageExtraction.java

private static String getTextContent(Part p) throws IOException, MessagingException {
    try {/*  w ww.  j  a  v a2s.  c om*/
        return (String) p.getContent();
    } catch (UnsupportedEncodingException e) {
        OutputStream os = new ByteArrayOutputStream();
        p.writeTo(os);
        String raw = os.toString();
        os.close();

        //cp932 -> Windows-31J
        raw = raw.replaceAll("cp932", "Windows-31J");

        InputStream is = new ByteArrayInputStream(raw.getBytes());
        Part newPart = new MimeBodyPart(is);
        is.close();

        return (String) newPart.getContent();
    }
}

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

/**
 * Creates a MimeBodyPart from a Part. If part is an instance of MimeBodyPart the part is returned without 
 * any modification./*w  w w  .java2  s  . co  m*/
 */
public static MimeBodyPart toMimeBodyPart(Part part) throws MessagingException, IOException {
    if (part instanceof MimeBodyPart) {
        return (MimeBodyPart) part;
    }

    byte[] bytes = MailUtils.partToByteArray(part);

    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

    MimeBodyPart mimeBodyPart = new MimeBodyPart(bis);

    return mimeBodyPart;
}

From source file:org.apache.olingo.fit.V4Services.java

@Override
public InputStream exploreMultipart(final List<Attachment> attachments, final String boundary,
        final boolean continueOnError) throws IOException {

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    Response res = null;//from   w  w w  .j ava  2  s. c om
    boolean goon = true;
    for (int i = 0; i < attachments.size() && goon; i++) {
        try {
            final Attachment obj = attachments.get(i);
            bos.write(("--" + boundary).getBytes());
            bos.write(Constants.CRLF);

            final Object content = obj.getDataHandler().getContent();
            if (content instanceof MimeMultipart) {
                final ByteArrayOutputStream chbos = new ByteArrayOutputStream();
                String lastContebtID = null;
                try {
                    final Map<String, String> references = new HashMap<String, String>();

                    final String cboundary = "changeset_" + UUID.randomUUID().toString();
                    chbos.write(("Content-Type: multipart/mixed;boundary=" + cboundary).getBytes());
                    chbos.write(Constants.CRLF);
                    chbos.write(Constants.CRLF);

                    for (int j = 0; j < ((MimeMultipart) content).getCount(); j++) {
                        final MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) content).getBodyPart(j);
                        lastContebtID = part.getContentID();
                        addChangesetItemIntro(chbos, lastContebtID, cboundary);

                        res = bodyPartRequest(new MimeBodyPart(part.getInputStream()), references);
                        if (!continueOnError && (res == null || res.getStatus() >= 400)) {
                            throw new Exception("Failure processing changeset");
                        }

                        addSingleBatchResponse(res, lastContebtID, chbos);
                        references.put("$" + lastContebtID, res.getHeaderString("Location"));
                    }

                    chbos.write(("--" + cboundary + "--").getBytes());
                    chbos.write(Constants.CRLF);

                    bos.write(chbos.toByteArray());
                    IOUtils.closeQuietly(chbos);
                } catch (Exception e) {
                    LOG.warn("While processing changeset", e);
                    IOUtils.closeQuietly(chbos);

                    addItemIntro(bos, lastContebtID);

                    if (res == null || res.getStatus() < 400) {
                        addErrorBatchResponse(e, "1", bos);
                    } else {
                        addSingleBatchResponse(res, lastContebtID, bos);
                    }

                    goon = continueOnError;
                }
            } else {
                addItemIntro(bos);

                res = bodyPartRequest(new MimeBodyPart(obj.getDataHandler().getInputStream()));

                if (res.getStatus() >= 400) {
                    goon = continueOnError;
                    throw new Exception("Failure processing batch item");
                }

                addSingleBatchResponse(res, bos);
            }
        } catch (Exception e) {
            if (res == null || res.getStatus() < 400) {
                addErrorBatchResponse(e, bos);
            } else {
                addSingleBatchResponse(res, bos);
            }
        }
    }

    bos.write(("--" + boundary + "--").getBytes());

    return new ByteArrayInputStream(bos.toByteArray());
}