Example usage for javax.mail.internet MimeMultipart getBodyPart

List of usage examples for javax.mail.internet MimeMultipart getBodyPart

Introduction

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

Prototype

public synchronized BodyPart getBodyPart(String CID) throws MessagingException 

Source Link

Document

Get the MimeBodyPart referred to by the given ContentID (CID).

Usage

From source file:ca.airspeed.demo.testingemail.EmailServiceTest.java

/**
 * When we send out an email with just a text body, et expect to get a
 * Multipart email having only a plain text body.
 *//*  ww w. j ava  2s.co  m*/
@Test
public void testSimpleEmail() throws Exception {
    // Given:
    EmailService service = makeALocalMailer();

    InternetAddress expectedTo = new InternetAddress("Indiana.Jones@domain.com", "Indiana Jones");
    String expectedSubject = "This is a Test Email";
    String expectedTextBody = "This is a simple test.";

    // When:
    service.sendSimpleEmail(expectedTo, expectedSubject, expectedTextBody);

    // Then:
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals("Number of messages sent;", 1, messages.size());

    WiserMessage message = messages.get(0);
    assertNotNull("No message was actually sent.", message);
    MimeMessage mimeMessage = message.getMimeMessage();
    Address[] toRecipients = mimeMessage.getRecipients(RecipientType.TO);
    assertEquals("Number of To: Recipient;", 1, toRecipients.length);
    Address toRecipient = toRecipients[0];
    assertEquals("To: Recipient;", expectedTo, toRecipient);

    InternetAddress expectedFrom = new InternetAddress("admin@domain.com", "Domain Admin");
    Address[] fromArr = mimeMessage.getFrom();
    assertEquals("From: email addresses;", 1, fromArr.length);
    assertEquals("Email From: address,", expectedFrom, fromArr[0]);

    assertEquals("Subject;", expectedSubject, mimeMessage.getSubject());

    assertNotNull("The date of the email cannot be null.", mimeMessage.getSentDate());

    MimeMultipart body = ((MimeMultipart) mimeMessage.getContent());
    assertEquals("Number of MIME Parts in the body;", 1, body.getCount());
    MimeMultipart textPart = ((MimeMultipart) body.getBodyPart(0).getContent());
    assertEquals("Number of MIME parts in the text body;", 1, textPart.getCount());
    MimeBodyPart plainTextPart = ((MimeBodyPart) textPart.getBodyPart(0));
    assertTrue("Expected the plain text content to be text/plain.", plainTextPart.isMimeType("text/plain"));
    assertEquals("Text Body;", expectedTextBody, plainTextPart.getContent());
}

From source file:org.openmrs.contrib.metadatarepository.service.MailEngineTest.java

@Test
public void testSendMessageWithAttachment() throws Exception {
    final String ATTACHMENT_NAME = "boring-attachment.txt";

    //mock smtp server
    Wiser wiser = new Wiser();
    int port = 2525 + (int) (Math.random() * 100);
    mailSender.setPort(port);/*from   w w  w .  j  a  v  a2  s .  c  o m*/
    wiser.setPort(port);
    wiser.start();

    Date dte = new Date();
    String emailSubject = "grepster testSendMessageWithAttachment: " + dte;
    String emailBody = "Body of the grepster testSendMessageWithAttachment message sent at: " + dte;

    ClassPathResource cpResource = new ClassPathResource("/test-attachment.txt");
    // a null from should work
    mailEngine.sendMessage(new String[] { "foo@bar.com" }, null, cpResource, emailBody, emailSubject,
            ATTACHMENT_NAME);

    mailEngine.sendMessage(new String[] { "foo@bar.com" }, mailMessage.getFrom(), cpResource, emailBody,
            emailSubject, ATTACHMENT_NAME);

    wiser.stop();
    // one without and one with from
    assertTrue(wiser.getMessages().size() == 2);

    WiserMessage wm = wiser.getMessages().get(0);
    MimeMessage mm = wm.getMimeMessage();

    Object o = wm.getMimeMessage().getContent();
    assertTrue(o instanceof MimeMultipart);
    MimeMultipart multi = (MimeMultipart) o;
    int numOfParts = multi.getCount();

    boolean hasTheAttachment = false;
    for (int i = 0; i < numOfParts; i++) {
        BodyPart bp = multi.getBodyPart(i);
        String disp = bp.getDisposition();
        if (disp == null) { //the body of the email
            Object innerContent = bp.getContent();
            MimeMultipart innerMulti = (MimeMultipart) innerContent;
            assertEquals(emailBody, innerMulti.getBodyPart(0).getContent());
        } else if (disp.equals(Part.ATTACHMENT)) { //the attachment to the email
            hasTheAttachment = true;
            assertEquals(ATTACHMENT_NAME, bp.getFileName());
        } else {
            fail("Did not expect to be able to get here.");
        }
    }
    assertTrue(hasTheAttachment);
    assertEquals(emailSubject, mm.getSubject());
}

From source file:org.apache.nifi.processors.standard.TestPutEmail.java

@Test
public void testOutgoingMessageAttachment() throws Exception {
    // verifies that are set on the outgoing Message correctly
    runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
    runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
    runner.setProperty(PutEmail.FROM, "test@apache.org");
    runner.setProperty(PutEmail.MESSAGE, "Message Body");
    runner.setProperty(PutEmail.ATTACH_FILE, "true");
    runner.setProperty(PutEmail.CONTENT_TYPE, "text/html");
    runner.setProperty(PutEmail.TO, "recipient@apache.org");

    runner.enqueue("Some text".getBytes());

    runner.run();//from ww w . j  a  va2s .  c o  m

    runner.assertQueueEmpty();
    runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);

    // Verify that the Message was populated correctly
    assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
    Message message = processor.getMessages().get(0);
    assertEquals("test@apache.org", message.getFrom()[0].toString());
    assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
    assertEquals("recipient@apache.org", message.getRecipients(RecipientType.TO)[0].toString());

    assertTrue(message.getContent() instanceof MimeMultipart);

    final MimeMultipart multipart = (MimeMultipart) message.getContent();
    final BodyPart part = multipart.getBodyPart(0);
    final InputStream is = part.getDataHandler().getInputStream();
    final String decodedText = StringUtils.newStringUtf8(Base64.decodeBase64(IOUtils.toString(is, "UTF-8")));
    assertEquals("Message Body", decodedText);

    final BodyPart attachPart = multipart.getBodyPart(1);
    final InputStream attachIs = attachPart.getDataHandler().getInputStream();
    final String text = IOUtils.toString(attachIs, "UTF-8");
    assertEquals("Some text", text);

    assertNull(message.getRecipients(RecipientType.BCC));
    assertNull(message.getRecipients(RecipientType.CC));
}

From source file:com.hmsinc.epicenter.surveillance.notification.MailingEventNotifierTest.java

private InputStream getMessageAsStream() throws IOException, MessagingException {
    MimeMessage message = (MimeMessage) sentMessages.get(0);
    MimeMultipart mm = (MimeMultipart) message.getContent();
    MimeBodyPart body0 = (MimeBodyPart) mm.getBodyPart(0);
    return body0.getInputStream();
}

From source file:se.inera.axel.shs.camel.ShsMessageDataFormatTest.java

@DirtiesContext
@Test// w  w w.  jav  a  2 s.  co  m
public void testMarshal() throws Exception {
    Assert.assertNotNull(testShsMessage);

    resultEndpoint.expectedMessageCount(1);
    template.sendBody("direct:marshal", testShsMessage);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getReceivedExchanges();
    Exchange exchange = exchanges.get(0);

    InputStream mimeStream = exchange.getIn().getBody(InputStream.class);

    MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(System.getProperties()), mimeStream);
    String[] mimeSubject = mimeMessage.getHeader("Subject");
    Assert.assertTrue("SHS Message".equalsIgnoreCase(mimeSubject[0]),
            "Subject is expected to be 'SHS Message' but was " + mimeSubject[0]);

    Assert.assertNull(mimeMessage.getMessageID());

    MimeMultipart multipart = (MimeMultipart) mimeMessage.getContent();
    Assert.assertEquals(multipart.getCount(), 2);

    BodyPart bodyPart = multipart.getBodyPart(1);
    String content = (String) bodyPart.getContent();
    Assert.assertEquals(content, ShsMessageTestObjectMother.DEFAULT_TEST_BODY);

    String contentType = bodyPart.getContentType();
    Assert.assertTrue(
            StringUtils.contains(contentType, ShsMessageTestObjectMother.DEFAULT_TEST_DATAPART_CONTENTTYPE),
            "Content type error");

    String encodings[] = bodyPart.getHeader("Content-Transfer-Encoding");
    Assert.assertNotNull(encodings);
    Assert.assertEquals(encodings.length, 1);
    Assert.assertEquals(encodings[0].toUpperCase(),
            ShsMessageTestObjectMother.DEFAULT_TEST_DATAPART_TRANSFERENCODING.toString().toUpperCase());

    mimeMessage.writeTo(System.out);
}

From source file:eu.peppol.as2.MdnMimeMessageInspector.java

/**
 * Return the fist part which have the given contentType
 *
 * @param contentType the mime type to look for
 *///from  w ww. ja  va  2  s  .  c o m
private BodyPart getPartFromMultipartReport(String contentType) {
    try {
        MimeMultipart multipartReport = getMultipartReport();
        for (int t = 0; t < multipartReport.getCount(); t++) {
            BodyPart bp = multipartReport.getBodyPart(t);
            if (bp.getContentType().contains(contentType))
                return bp;
        }
    } catch (Exception e) {
        log.error("Failed to locate part of multipart/report of type " + contentType);
    }
    return null;
}

From source file:com.hmsinc.epicenter.surveillance.notification.MailingEventNotifierTest.java

@Test
public void shouldHaveCorrectStructure() throws MessagingException, IOException {
    MimeMessage message = (MimeMessage) sentMessages.get(0);

    MimeMultipart mm = (MimeMultipart) message.getContent();
    assertEquals(1, mm.getCount());/*ww w.ja v  a2  s  . co  m*/

    MimeBodyPart body0 = (MimeBodyPart) mm.getBodyPart(0);
    assertNotNull(loadContent(body0.getInputStream()));
}

From source file:com.adobe.acs.commons.email.EmailServiceImplTest.java

@Test
public final void testSendEmailAttachment() throws Exception {

    final String expectedMessage = "This is just a message";
    final String expectedSenderName = "John Smith";
    final String expectedSenderEmailAddress = "john@smith.com";
    String attachment = "This is a attachment.";
    String attachmentName = "attachment.txt";
    //Subject is provided inside the HtmlTemplate directly
    final String expectedSubject = "Greetings";

    final Map<String, String> params = new HashMap<String, String>();
    params.put("message", expectedMessage);
    params.put("senderName", expectedSenderName);
    params.put("senderEmailAddress", expectedSenderEmailAddress);

    final String recipient = "upasanac@acs.com";

    Map<String, DataSource> attachments = new HashMap();
    attachments.put(attachmentName, new ByteArrayDataSource(attachment, "text/plain"));

    ArgumentCaptor<HtmlEmail> captor = ArgumentCaptor.forClass(HtmlEmail.class);

    List<String> failureList = emailService.sendEmail(emailTemplateAttachmentPath, params, attachments,
            recipient);//from w  w w. jav a 2  s . c  o m

    verify(messageGatewayHtmlEmail, times(1)).send(captor.capture());

    assertEquals(expectedSenderEmailAddress, captor.getValue().getFromAddress().getAddress());
    assertEquals(expectedSenderName, captor.getValue().getFromAddress().getPersonal());
    assertEquals(expectedSubject, captor.getValue().getSubject());
    assertEquals(recipient, captor.getValue().getToAddresses().get(0).toString());
    Method getContainer = captor.getValue().getClass().getSuperclass().getDeclaredMethod("getContainer");
    getContainer.setAccessible(true);
    MimeMultipart mimeMultipart = (MimeMultipart) getContainer.invoke(captor.getValue());
    getContainer.setAccessible(false);
    assertEquals(attachment, mimeMultipart.getBodyPart(0).getContent().toString());

    //If email is sent to the recipient successfully, the response is an empty failureList
    assertTrue(failureList.isEmpty());
}

From source file:cherry.foundation.mail.MailSendHandlerImplTest.java

@Test
public void testSendNowAttached() throws Exception {
    LocalDateTime now = LocalDateTime.now();
    MailSendHandler handler = create(now);

    ArgumentCaptor<MimeMessagePreparator> preparator = ArgumentCaptor.forClass(MimeMessagePreparator.class);
    doNothing().when(mailSender).send(preparator.capture());

    final File file = File.createTempFile("test_", ".txt", new File("."));
    file.deleteOnExit();/*ww w.j  a  v  a  2 s. c  o  m*/
    try {

        try (OutputStream out = new FileOutputStream(file)) {
            out.write("attach2".getBytes());
        }

        final DataSource dataSource = new DataSource() {
            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getName() {
                return "name3.txt";
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream("attach3".getBytes());
            }

            @Override
            public String getContentType() {
                return "text/plain";
            }
        };

        long messageId = handler.sendNow("loginId", "messageName", "from@addr", asList("to@addr"),
                asList("cc@addr"), asList("bcc@addr"), "subject", "body", new AttachmentPreparator() {
                    @Override
                    public void prepare(Attachment attachment) throws MessagingException {
                        attachment.add("name0.txt", new ByteArrayResource("attach0".getBytes()));
                        attachment.add("name1.bin", new ByteArrayResource("attach1".getBytes()),
                                "application/octet-stream");
                        attachment.add("name2.txt", file);
                        attachment.add("name3.txt", dataSource);
                    }
                });

        Session session = Session.getDefaultInstance(new Properties());
        MimeMessage message = new MimeMessage(session);
        preparator.getValue().prepare(message);

        assertEquals(0L, messageId);
        assertEquals(1, message.getRecipients(RecipientType.TO).length);
        assertEquals(parse("to@addr")[0], message.getRecipients(RecipientType.TO)[0]);
        assertEquals(1, message.getRecipients(RecipientType.CC).length);
        assertEquals(parse("cc@addr")[0], message.getRecipients(RecipientType.CC)[0]);
        assertEquals(1, message.getRecipients(RecipientType.BCC).length);
        assertEquals(parse("bcc@addr")[0], message.getRecipients(RecipientType.BCC)[0]);
        assertEquals(1, message.getFrom().length);
        assertEquals(parse("from@addr")[0], message.getFrom()[0]);
        assertEquals("subject", message.getSubject());

        MimeMultipart mm = (MimeMultipart) message.getContent();
        assertEquals(5, mm.getCount());
        assertEquals("body", ((MimeMultipart) mm.getBodyPart(0).getContent()).getBodyPart(0).getContent());

        assertEquals("name0.txt", mm.getBodyPart(1).getFileName());
        assertEquals("text/plain", mm.getBodyPart(1).getContentType());
        assertEquals("attach0", mm.getBodyPart(1).getContent());

        assertEquals("name1.bin", mm.getBodyPart(2).getDataHandler().getName());
        assertEquals("application/octet-stream", mm.getBodyPart(2).getDataHandler().getContentType());
        assertEquals("attach1", new String(
                ByteStreams.toByteArray((InputStream) mm.getBodyPart(2).getDataHandler().getContent())));

        assertEquals("name2.txt", mm.getBodyPart(3).getFileName());
        assertEquals("text/plain", mm.getBodyPart(3).getContentType());
        assertEquals("attach2", mm.getBodyPart(3).getContent());

        assertEquals("name3.txt", mm.getBodyPart(4).getFileName());
        assertEquals("text/plain", mm.getBodyPart(4).getContentType());
        assertEquals("attach3", mm.getBodyPart(4).getContent());
    } finally {
        file.delete();
    }
}

From source file:org.nuxeo.ecm.platform.mail.action.TransformMessageAction.java

private void processMultipartMessage(MimeMultipart parts) throws MessagingException, IOException {
    log.debug("processing multipart message.");
    for (int i = 0; i < parts.getCount(); i++) {
        Part part = parts.getBodyPart(i);
        if (part.getDataHandler().getContent() instanceof MimeMultipart) {
            log.debug("** found embedded multipart message");
            processMultipartMessage((MimeMultipart) part.getDataHandler().getContent());
            continue;
        }// w w  w . jav  a  2s.co m
        log.debug("processing single part message: " + part.getClass());
        processSingleMessagePart(part);
    }
}