Example usage for javax.mail BodyPart getHeader

List of usage examples for javax.mail BodyPart getHeader

Introduction

In this page you can find the example usage for javax.mail BodyPart getHeader.

Prototype

public String[] getHeader(String header_name) throws MessagingException;

Source Link

Document

Get all the headers for this header name.

Usage

From source file:org.geoserver.wcs.GetCoverageTest.java

/**
 * This tests just ended up throwing an exception as the coverage being encoded
 * was too large due to a bug in the scales estimation
 * //  ww  w.  j ava2s. c o m
 * @throws Exception
 */
@Test
public void testRotatedGet() throws Exception {
    String request = "wcs?&service=WCS&request=GetCoverage&version=1.1.1&identifier=RotatedCad&BoundingBox=7.7634071540971386,45.14712131948007,7.76437367395267,45.14764567708965,urn:ogc:def:crs:OGC:1.3:CRS84&Format=image/tiff";
    MockHttpServletResponse response = getAsServletResponse(request);

    // parse the multipart, check there are two parts
    Multipart multipart = getMultipart(response);
    assertEquals(2, multipart.getCount());
    BodyPart coveragePart = multipart.getBodyPart(1);
    assertEquals("image/tiff", coveragePart.getContentType());
    assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]);

    // make sure we can read the coverage back
    ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next();
    reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream()));
    RenderedImage image = reader.read(0);

    // check the image is suitably small (without requiring an exact size)
    assertTrue(image.getWidth() < 1000);
    assertTrue(image.getHeight() < 1000);
}

From source file:org.mule.module.http.internal.HttpParser.java

public static Collection<HttpPart> parseMultipartContent(InputStream content, String contentType)
        throws IOException {
    MimeMultipart mimeMultipart = null;/* ww  w .j  a va2s . c  o  m*/
    List<HttpPart> parts = Lists.newArrayList();

    try {
        mimeMultipart = new MimeMultipart(new ByteArrayDataSource(content, contentType));
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    try {
        int partCount = mimeMultipart.getCount();

        for (int i = 0; i < partCount; i++) {
            BodyPart part = mimeMultipart.getBodyPart(i);

            String filename = part.getFileName();
            String partName = filename;
            String[] contentDispositions = part.getHeader(CONTENT_DISPOSITION_PART_HEADER);
            if (contentDispositions != null) {
                String contentDisposition = contentDispositions[0];
                if (contentDisposition.contains(NAME_ATTRIBUTE)) {
                    partName = contentDisposition.substring(
                            contentDisposition.indexOf(NAME_ATTRIBUTE) + NAME_ATTRIBUTE.length() + 2);
                    partName = partName.substring(0, partName.indexOf("\""));
                }
            }
            HttpPart httpPart = new HttpPart(partName, filename, IOUtils.toByteArray(part.getInputStream()),
                    part.getContentType(), part.getSize());

            Enumeration<Header> headers = part.getAllHeaders();

            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                httpPart.addHeader(header.getName(), header.getValue());
            }
            parts.add(httpPart);
        }
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    return parts;
}

From source file:org.mule.service.http.impl.service.server.grizzly.HttpParser.java

public static Collection<HttpPart> parseMultipartContent(InputStream content, String contentType)
        throws IOException {
    MimeMultipart mimeMultipart = null;//from  w  ww  . ja va  2 s.co m
    List<HttpPart> parts = Lists.newArrayList();

    try {
        mimeMultipart = new MimeMultipart(new ByteArrayDataSource(content, contentType));
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    try {
        int partCount = mimeMultipart.getCount();

        for (int i = 0; i < partCount; i++) {
            BodyPart part = mimeMultipart.getBodyPart(i);

            String filename = part.getFileName();
            String partName = filename;
            String[] contentDispositions = part.getHeader(CONTENT_DISPOSITION);
            if (contentDispositions != null) {
                String contentDisposition = contentDispositions[0];
                if (contentDisposition.contains(NAME_ATTRIBUTE)) {
                    partName = contentDisposition.substring(
                            contentDisposition.indexOf(NAME_ATTRIBUTE) + NAME_ATTRIBUTE.length() + 2);
                    partName = partName.substring(0, partName.indexOf("\""));
                }
            }

            if (partName == null && mimeMultipart.getContentType().contains(MULTIPART_RELATED.toString())) {
                String[] contentIdHeader = part.getHeader(CONTENT_ID);
                if (contentIdHeader != null && contentIdHeader.length > 0) {
                    partName = contentIdHeader[0];
                }
            }

            HttpPart httpPart = new HttpPart(partName, filename, IOUtils.toByteArray(part.getInputStream()),
                    part.getContentType(), part.getSize());

            Enumeration<Header> headers = part.getAllHeaders();

            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                httpPart.addHeader(header.getName(), header.getValue());
            }
            parts.add(httpPart);
        }
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    return parts;
}

From source file:org.xwiki.mail.integration.JavaIntegrationTest.java

@Test
public void sendTextMail() throws Exception {
    // Step 1: Create a JavaMail Session
    Session session = Session.getInstance(this.configuration.getAllProperties());

    // Step 2: Create the Message to send
    MimeMessage message = new MimeMessage(session);
    message.setSubject("subject");
    message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));

    // Step 3: Add the Message Body
    Multipart multipart = new MimeMultipart("mixed");
    // Add text in the body
    multipart.addBodyPart(this.defaultBodyPartFactory.create("some text here",
            Collections.<String, Object>singletonMap("mimetype", "text/plain")));
    message.setContent(multipart);//ww w .  ja va2s. c  o  m

    // We also test using some default BCC addresses from configuration in this test
    this.configuration.setBCCAddresses(Arrays.asList("bcc1@doe.com", "bcc2@doe.com"));

    // Ensure we do not reuse the same message identifier for multiple similar messages in this test
    MimeMessage message2 = new MimeMessage(message);
    message2.saveChanges();
    MimeMessage message3 = new MimeMessage(message);
    message3.saveChanges();

    // Step 4: Send the mail and wait for it to be sent
    // Send 3 mails (3 times the same mail) to verify we can send several emails at once.
    MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory");
    this.sender.sendAsynchronously(Arrays.asList(message, message2, message3), session, memoryMailListener);

    // Note: we don't test status reporting from the listener since this is already tested in the
    // ScriptingIntegrationTest test class.

    // Verify that the mails have been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 3);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    // Note: we're receiving 9 messages since we sent 3 with 3 recipients (2 BCC and 1 to)!
    assertEquals(9, messages.length);

    // Assert the email parts that are the same for all mails
    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals(1, ((MimeMultipart) messages[0].getContent()).getCount());
    BodyPart textBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
    assertEquals("text/plain", textBodyPart.getHeader("Content-Type")[0]);
    assertEquals("some text here", textBodyPart.getContent());
    assertEquals("john@doe.com", messages[0].getHeader("To", null));

    // Note: We cannot assert that the BCC worked since by definition BCC information are not visible in received
    // messages ;) But we checked that we received 9 emails above so that's good enough.
}

From source file:org.xwiki.mail.integration.JavaIntegrationTest.java

@Test
public void sendHTMLAndCalendarInvitationMail() throws Exception {
    // Step 1: Create a JavaMail Session
    Session session = Session.getInstance(this.configuration.getAllProperties());

    // Step 2: Create the Message to send
    MimeMessage message = new MimeMessage(session);
    message.setSubject("subject");
    message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));

    // Step 3: Add the Message Body
    Multipart multipart = new MimeMultipart("alternative");
    // Add an HTML body part
    multipart.addBodyPart(/*from   www. j av  a  2 s .  c o  m*/
            this.htmlBodyPartFactory.create("<font size=\"\\\"2\\\"\">simple meeting invitation</font>",
                    Collections.<String, Object>emptyMap()));
    // Add the Calendar invitation body part
    String calendarContent = "BEGIN:VCALENDAR\r\n" + "METHOD:REQUEST\r\n" + "PRODID: Meeting\r\n"
            + "VERSION:2.0\r\n" + "BEGIN:VEVENT\r\n" + "DTSTAMP:20140616T164100\r\n"
            + "DTSTART:20140616T164100\r\n" + "DTEND:20140616T194100\r\n" + "SUMMARY:test request\r\n"
            + "UID:324\r\n"
            + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:john@doe.com\r\n"
            + "ORGANIZER:MAILTO:john@doe.com\r\n" + "LOCATION:on the net\r\n"
            + "DESCRIPTION:learn some stuff\r\n" + "SEQUENCE:0\r\n" + "PRIORITY:5\r\n" + "CLASS:PUBLIC\r\n"
            + "STATUS:CONFIRMED\r\n" + "TRANSP:OPAQUE\r\n" + "BEGIN:VALARM\r\n" + "ACTION:DISPLAY\r\n"
            + "DESCRIPTION:REMINDER\r\n" + "TRIGGER;RELATED=START:-PT00H15M00S\r\n" + "END:VALARM\r\n"
            + "END:VEVENT\r\n" + "END:VCALENDAR";
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("mimetype", "text/calendar;method=CANCEL");
    parameters.put("headers", Collections.singletonMap("Content-Class", "urn:content-classes:calendarmessage"));
    multipart.addBodyPart(this.defaultBodyPartFactory.create(calendarContent, parameters));

    message.setContent(multipart);

    // Step 4: Send the mail and wait for it to be sent
    this.sender.sendAsynchronously(Arrays.asList(message), session, null);

    // Verify that the mail has been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 1);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals("john@doe.com", messages[0].getHeader("To", null));

    assertEquals(2, ((MimeMultipart) messages[0].getContent()).getCount());

    BodyPart htmlBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
    assertEquals("text/html; charset=UTF-8", htmlBodyPart.getHeader("Content-Type")[0]);
    assertEquals("<font size=\"\\\"2\\\"\">simple meeting invitation</font>", htmlBodyPart.getContent());

    BodyPart calendarBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(1);
    assertEquals("text/calendar;method=CANCEL", calendarBodyPart.getHeader("Content-Type")[0]);
    InputStream is = (InputStream) calendarBodyPart.getContent();
    assertEquals(calendarContent, IOUtils.toString(is));
}

From source file:org.xwiki.mail.integration.ScriptingIntegrationTest.java

@Test
public void sendTextMail() throws Exception {
    ScriptMimeMessage message1 = this.scriptService.createMessage("john@doe.com", "subject");
    message1.addPart("text/plain", "some text here");
    ScriptMimeMessage message2 = this.scriptService.createMessage("john@doe.com", "subject");
    message2.addPart("text/plain", "some text here");
    ScriptMimeMessage message3 = this.scriptService.createMessage("john@doe.com", "subject");
    message3.addPart("text/plain", "some text here");

    // Send 3 mails (3 times the same mail) to verify we can send several emails at once.
    List<ScriptMimeMessage> messagesList = Arrays.asList(message1, message2, message3);
    ScriptMailResult result = this.scriptService.sendAsynchronously(messagesList, "memory");

    // Verify that there are no errors
    assertNull(this.scriptService.getLastError());

    // Wait for all mails to be sent
    result.getStatusResult().waitTillProcessed(30000L);
    assertTrue(result.getStatusResult().isProcessed());

    // Verify that all mails have been sent properly
    assertFalse("There should not be any failed result!",
            result.getStatusResult().getByState(MailState.SEND_ERROR).hasNext());
    assertFalse("There should not be any failed result!",
            result.getStatusResult().getByState(MailState.PREPARE_ERROR).hasNext());
    assertFalse("There should not be any mails in the ready state!",
            result.getStatusResult().getByState(MailState.PREPARE_SUCCESS).hasNext());

    // Verify that the mails have been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 3);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    assertEquals(3, messages.length);/*ww w .ja va 2s. c o  m*/
    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals("john@doe.com", messages[0].getHeader("To", null));

    assertEquals(1, ((MimeMultipart) messages[0].getContent()).getCount());

    BodyPart textBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
    assertEquals("text/plain", textBodyPart.getHeader("Content-Type")[0]);
    assertEquals("some text here", textBodyPart.getContent());
}

From source file:org.xwiki.mail.integration.ScriptingIntegrationTest.java

@Test
public void sendHTMLAndCalendarInvitationMail() throws Exception {
    ScriptMimeMessage message = this.scriptService.createMessage("john@doe.com", "subject");
    message.addPart("text/html", "<font size=\"\\\"2\\\"\">simple meeting invitation</font>");
    // @formatter:off
    String calendarContent = "BEGIN:VCALENDAR\r\n" + "METHOD:REQUEST\r\n" + "PRODID: Meeting\r\n"
            + "VERSION:2.0\r\n" + "BEGIN:VEVENT\r\n" + "DTSTAMP:20140616T164100\r\n"
            + "DTSTART:20140616T164100\r\n" + "DTEND:20140616T194100\r\n" + "SUMMARY:test request\r\n"
            + "UID:324\r\n"
            + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:john@doe.com\r\n"
            + "ORGANIZER:MAILTO:john@doe.com\r\n" + "LOCATION:on the net\r\n"
            + "DESCRIPTION:learn some stuff\r\n" + "SEQUENCE:0\r\n" + "PRIORITY:5\r\n" + "CLASS:PUBLIC\r\n"
            + "STATUS:CONFIRMED\r\n" + "TRANSP:OPAQUE\r\n" + "BEGIN:VALARM\r\n" + "ACTION:DISPLAY\r\n"
            + "DESCRIPTION:REMINDER\r\n" + "TRIGGER;RELATED=START:-PT00H15M00S\r\n" + "END:VALARM\r\n"
            + "END:VEVENT\r\n" + "END:VCALENDAR";
    // @formatter:on
    message.addPart("text/calendar;method=CANCEL", calendarContent, Collections.<String, Object>singletonMap(
            "headers", Collections.singletonMap("Content-Class", "urn:content-classes:calendarmessage")));

    ScriptMailResult result = this.scriptService.send(Arrays.asList(message));

    // Verify that there are no errors and that 1 mail was sent
    assertNull(this.scriptService.getLastError());
    assertTrue(result.getStatusResult().isProcessed());
    assertEquals(1, result.getStatusResult().getProcessedMailCount());

    // Verify that all mails have been sent properly
    assertFalse("There should not be any failed result!",
            result.getStatusResult().getByState(MailState.SEND_ERROR).hasNext());
    assertFalse("There should not be any failed result!",
            result.getStatusResult().getByState(MailState.PREPARE_ERROR).hasNext());
    assertFalse("There should not be any mails in the ready state!",
            result.getStatusResult().getByState(MailState.PREPARE_SUCCESS).hasNext());

    // Verify that the mail has been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 1);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    assertEquals(1, messages.length);/*from  ww  w  .  j a  va2 s. c  o m*/
    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals("john@doe.com", messages[0].getHeader("To", null));

    assertEquals(2, ((MimeMultipart) messages[0].getContent()).getCount());

    BodyPart htmlBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
    assertEquals("text/html", htmlBodyPart.getHeader("Content-Type")[0]);
    assertEquals("<font size=\"\\\"2\\\"\">simple meeting invitation</font>", htmlBodyPart.getContent());

    BodyPart calendarBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(1);
    assertEquals("text/calendar;method=CANCEL", calendarBodyPart.getHeader("Content-Type")[0]);
    InputStream is = (InputStream) calendarBodyPart.getContent();
    assertEquals(calendarContent, IOUtils.toString(is));
}