Example usage for javax.mail.internet MimeMultipart getCount

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

Introduction

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

Prototype

@Override
public synchronized int getCount() throws MessagingException 

Source Link

Document

Return the number of enclosed BodyPart objects.

Usage

From source file:com.it.j2ee.email.MailServiceTest.java

@Test
public void sendMimeMail() throws InterruptedException, MessagingException, IOException {
    mimeMailService.sendNotificationMail("calvin");

    greenMail.waitForIncomingEmail(2000, 1);
    MimeMessage[] messages = greenMail.getReceivedMessages();
    MimeMessage message = messages[messages.length - 1];

    assertThat(message.getFrom()[0].toString()).isEqualTo("springside3.demo@gmail.com");
    assertThat(message.getSubject()).isEqualTo("");

    MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();

    assertThat(mimeMultipart.getCount()).isEqualTo(2);

    // Html?//from  w ww .  j a  v a  2  s .c  om
    String mainPartText = getMainPartText(mimeMultipart.getBodyPart(0));
    System.out.println(mainPartText);
    assertThat(mainPartText).contains("<h1>calvin.</h1>");

    // 
    assertThat(GreenMailUtil.getBody(mimeMultipart.getBodyPart(1)).trim())
            .isEqualTo("Hello,i am a attachment.");
}

From source file:org.openhie.openempi.service.MailEngineTest.java

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);// ww w .  j ava2  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");
    mailEngine.sendMessage(new String[] { "foo@bar.com" }, mailMessage.getFrom(), cpResource, emailBody,
            emailSubject, ATTACHMENT_NAME);

    wiser.stop();
    assertTrue(wiser.getMessages().size() == 1);
    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.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  ww .  j  a  va  2s .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:com.adaptris.util.text.mime.ByteArrayIterator.java

@Override
protected void initIterator() throws MessagingException, IOException {
    bodyParts = new Vector<BytePartHolder>();
    MimeMultipart multipart = new MimeMultipart(dataSource);
    for (int i = 0; i < multipart.getCount(); i++) {
        MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(i);
        BytePartHolder ph = new BytePartHolder(part);
        if (bodyParts.contains(ph)) {
            log.warn("{} already exists as a part", ph.contentId);
        }/* w  w  w  .  j  av  a  2 s.c om*/
        bodyParts.add(ph);
    }
    bodyPartIterator = bodyParts.iterator();
}

From source file:org.alfresco.cacheserver.MultipartTest.java

private List<Patch> getPatches(String nodeId, long nodeVersion) throws MessagingException, IOException {
    List<Patch> patches = new LinkedList<>();

    StringBuilder sb = new StringBuilder();
    sb.append("/patch/");
    sb.append(nodeId);/*  ww w .jav a2s  .com*/
    sb.append("/");
    sb.append(nodeVersion);
    String url = sb.toString();

    final ClientConfig config = new DefaultClientConfig();
    config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    final Client client = Client.create(config);

    final WebResource resource = client.resource(url);
    final MimeMultipart response = resource.get(MimeMultipart.class);

    // This will iterate the individual parts of the multipart response
    for (int i = 0; i < response.getCount(); i++) {
        final BodyPart part = response.getBodyPart(i);
        System.out.printf("Embedded Body Part [Mime Type: %s, Length: %s]\n", part.getContentType(),
                part.getSize());
        InputStream in = part.getInputStream();
        //          Patch patch = new Patch();
        //          patches.add(patch);
    }

    return patches;
}

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

@Test
public void testWithAttachment() throws Exception {
    // Given://from  ww w .  j av  a 2s .  c om
    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 test with a PDF attachment.";
    List<FileSystemResource> filesToAttach = new ArrayList<FileSystemResource>();
    filesToAttach.add(
            new FileSystemResource(this.getClass().getClassLoader().getResource("HelloWorld.pdf").getFile()));

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

    // Then:
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals("Number of messages sent;", 1, messages.size());
    WiserMessage message = messages.get(0);
    MimeMessage mimeMessage = message.getMimeMessage();

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

    MimeMultipart body = ((MimeMultipart) mimeMessage.getContent());
    assertEquals("Number of MIME Parts in the body;", 2, body.getCount());

    MimeBodyPart attachment = ((MimeBodyPart) body.getBodyPart(1));
    assertTrue("Attachment MIME Type should be application/pdf", attachment.isMimeType("application/pdf"));
    assertEquals("Attachment filename;", "HelloWorld.pdf", attachment.getFileName());
    assertTrue("No content found in the attachment.", isNotBlank(attachment.getContent().toString()));
}

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.
 *///from  ww w.j  ava  2s .c  o  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:se.inera.axel.shs.camel.ShsMessageDataFormatTest.java

@DirtiesContext
@Test/*  w w  w  .  j  av a 2s . com*/
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:com.caris.oscarexchange4j.proxy.PreviewCoverage.java

@Override
public void processInputStream(InputStream is) throws Exception {
    try {//from   w w  w.  j av  a 2 s  .  c  o m
        MimeMultipart multiPart = new MimeMultipart(new ByteArrayDataSource(is, MULTI_PART_MIME_TYPE));
        int count = multiPart.getCount();
        for (int part = 0; part < count; part++) {
            BodyPart body = multiPart.getBodyPart(part);
            if (body.isMimeType(OUTPUT_MIME_TYPE)) {
                this.inputStream = body.getInputStream();
                break;
            }
        }
    } catch (Exception e) {
        this.inputStream = getErrorResponseStream();
    }
}

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
 *///w  w w.  ja va  2s.  co 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;
}