Example usage for javax.mail BodyPart getContent

List of usage examples for javax.mail BodyPart getContent

Introduction

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

Prototype

public Object getContent() throws IOException, MessagingException;

Source Link

Document

Return the content as a Java object.

Usage

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);/*from   ww w .j  a va 2 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:se.inera.axel.shs.camel.ShsMessageDataFormatTest.java

@DirtiesContext
@Test/*  ww w.  j  av  a  2s.c om*/
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: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 ww  w . j  a  va  2 s.  c om
    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:eu.peppol.as2.MdnMimeMessageInspector.java

/**
 * The multipart/report should contain both a text/plain part with textual information and
 * a message/disposition-notification part that should be examined for error/failure/warning.
 *//*from w  w  w  . jav a 2 s  . co  m*/
public MimeMultipart getMultipartReport() {
    try {
        BodyPart bodyPart = getSignedMultiPart().getBodyPart(0);
        Object content = bodyPart.getContent();
        MimeMultipart multipartReport = (MimeMultipart) content;
        if (!multipartReport.getContentType().contains("multipart/report")) {
            throw new IllegalStateException(
                    "The first body part of the first part of the signed message is not a multipart/report");
        }
        return multipartReport;
    } catch (Exception e) {
        throw new IllegalStateException("Unable to retrieve the multipart/report : " + e.getMessage(), e);
    }
}

From source file:mitm.application.djigzo.ca.PFXMailBuilderTest.java

@Test
public void testReplacePFXSendSMSFalse() throws Exception {
    byte[] pfx = IOUtils.toByteArray(new FileInputStream(testPFX));

    PFXMailBuilder builder = new PFXMailBuilder(IOUtils.toString(new FileInputStream(templateFile)),
            templateBuilder);//  w  ww  .  jav  a2s.c o  m

    String from = "123@test.com";

    builder.setFrom(new InternetAddress(from, "test user"));
    builder.setPFX(pfx);
    builder.addProperty("sendSMS", false);

    MimeMessage message = builder.createMessage();

    assertNotNull(message);

    MailUtils.writeMessage(message, new File(tempDir, "testReplacePFXSendSMSFalse.eml"));

    Multipart mp;

    mp = (Multipart) message.getContent();

    BodyPart textPart = mp.getBodyPart(0);

    assertTrue(textPart.isMimeType("text/plain"));

    String body = (String) textPart.getContent();

    assertFalse(body.contains("was sent to you by SMS"));

    /*
     * Check if the PFX has really been replaced
     */
    byte[] newPFX = getPFX(message);

    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new ByteArrayInputStream(newPFX), "test".toCharArray());

    assertEquals(22, keyStore.size());
}

From source file:mitm.application.djigzo.ca.PFXMailBuilderTest.java

@Test
public void testReplacePFXSendSMSTrue() throws Exception {
    byte[] pfx = IOUtils.toByteArray(new FileInputStream(testPFX));

    PFXMailBuilder builder = new PFXMailBuilder(IOUtils.toString(new FileInputStream(templateFile)),
            templateBuilder);/*from   w w w.  jav a  2 s. c  om*/

    String from = "123@test.com";

    builder.setFrom(new InternetAddress(from, "test user"));
    builder.setPFX(pfx);
    builder.addProperty("sendSMS", true);
    builder.addProperty("phoneNumberAnonymized", "1234***");
    builder.addProperty("id", "0987");

    MimeMessage message = builder.createMessage();

    assertNotNull(message);

    MailUtils.writeMessage(message, new File(tempDir, "testReplacePFXSendSMSTrue.eml"));

    Multipart mp;

    mp = (Multipart) message.getContent();

    BodyPart textPart = mp.getBodyPart(0);

    assertTrue(textPart.isMimeType("text/plain"));

    String body = (String) textPart.getContent();

    assertTrue(body.contains("was sent to you by SMS"));

    /*
     * Check if the PFX has really been replaced
     */
    byte[] newPFX = getPFX(message);

    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new ByteArrayInputStream(newPFX), "test".toCharArray());

    assertEquals(22, keyStore.size());
}

From source file:com.consol.citrus.mail.message.MailMessageConverter.java

/**
 * Construct multipart body with first part being the body content and further parts being the attachments.
 * @param body/*from   www. j a va2 s. com*/
 * @return
 * @throws IOException
 */
private BodyPart handleMultiPart(Multipart body) throws IOException, MessagingException {
    BodyPart bodyPart = null;
    for (int i = 0; i < body.getCount(); i++) {
        MimePart entity = (MimePart) body.getBodyPart(i);

        if (bodyPart == null) {
            bodyPart = handlePart(entity);
        } else {
            BodyPart attachment = handlePart(entity);
            bodyPart.addPart(new AttachmentPart(attachment.getContent(),
                    parseContentType(attachment.getContentType()), entity.getFileName()));
        }
    }

    return bodyPart;
}

From source file:com.seleniumtests.connectors.mails.ImapClient.java

/**
 * returns message parts//  www.  j a  va2 s  . com
 * @param content   
 * @return         message parts
 * @throws IOException
 * @throws MessagingException
 */
private List<BodyPart> getMessageParts(Multipart content) throws IOException, MessagingException {
    List<BodyPart> partList = new ArrayList<>();

    for (int partId = 0; partId < content.getCount(); partId++) {
        BodyPart part = content.getBodyPart(partId);

        if (part.getContentType().toLowerCase().contains("multipart/")) {

            partList.addAll(getMessageParts((Multipart) part.getContent()));
        } else {
            partList.add(part);
        }
    }

    return partList;
}

From source file:io.lavagna.service.MailTicketService.java

private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException {
    String result = "";
    int count = mimeMultipart.getCount();
    for (int i = 0; i < count; i++) {
        BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.isMimeType("text/plain")) {
            result = result + "\n" + bodyPart.getContent();
            break;
        } else if (bodyPart.isMimeType("text/html")) {
            String html = (String) bodyPart.getContent();
            result = result + "\n" + Jsoup.parse(html).text();
        } else if (bodyPart.getContent() instanceof MimeMultipart) {
            result = result + getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent());
        }/*from ww w  .  j a  v a2 s  .  com*/
    }
    return result;
}

From source file:org.github.alexwibowo.opentext.client.AxiomVRDClient.java

@Override
public void getDocument(String recordID, String section, String renditionType, VRDDocumentVersion version,
        OutputStream outputStream) throws Exception {
    // create vrd namespace without prefix. This is important, as crazy VRD doesnt like prefix.
    OMNamespace vrdNamespace = factory.createOMNamespace("http://record.webservices.rd.vignette.com/", "");

    OMElement getRenditionElement = factory.createOMElement("getRendition", vrdNamespace);

    OMElement recordIdElement = factory.createOMElement("recordID", vrdNamespace);
    recordIdElement.setText(recordID);/*from www . j a v  a  2s .c  o  m*/
    getRenditionElement.addChild(recordIdElement);

    OMElement sectionElement = factory.createOMElement("section", vrdNamespace);
    sectionElement.setText(section);
    getRenditionElement.addChild(sectionElement);

    OMElement subSectionElement = factory.createOMElement("subSection", vrdNamespace);
    subSectionElement.setText("0");
    getRenditionElement.addChild(subSectionElement);

    OMElement renditionTypeElement = factory.createOMElement("renditionType", vrdNamespace);
    renditionTypeElement.setText(StringUtils.isBlank(renditionType) ? "ORIGINAL" : renditionType);
    getRenditionElement.addChild(renditionTypeElement);

    OMElement versionElement = factory.createOMElement("version", vrdNamespace);
    versionElement.setText(version.name());
    getRenditionElement.addChild(versionElement);

    SOAPMessageBuilder soap11MessageBuilder = new AxiomSOAP11MessageBuilder(jaxbContext, soap11Factory)
            .withPayload(getRenditionElement)
            .withUsernameToken(configuration.getUsername(), configuration.getPassword());

    SOAPEnvelope envelope = (SOAPEnvelope) soap11MessageBuilder.build();
    HttpResponse httpResponse = postAsMultipart(envelope, GetRendition.getQName());

    if (httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() == 200) {
        if (httpResponse.getEntity() != null && httpResponse.getEntity().getContent() != null) {
            String contentType = httpResponse.getFirstHeader("Content-Type").getValue();
            InputStream responseAsStream = httpResponse.getEntity().getContent();

            MultipartHttpResponseDataSource dataSource = new MultipartHttpResponseDataSource(responseAsStream,
                    contentType);
            WibMimeMultipart mp = new WibMimeMultipart(dataSource);
            BodyPart bodyPart = mp.getBodyPart(1);

            ByteArrayInputStream content = (ByteArrayInputStream) bodyPart.getContent();
            copy(content, outputStream);
        } else {
            throw new GeneralVRDException("No valid response for getting document from VRD.", null); // need a better structure here..
        }
    } else {
        InputStream in = httpResponse.getEntity().getContent();
        SOAPEnvelope response = OMXMLBuilderFactory.createSOAPModelBuilder(in, "UTF-8").getSOAPEnvelope();
        OMElement fault = response.getBody()
                .getFirstChildWithName(new QName("http://schemas.xmlsoap.org/soap/envelope/", "Fault"));
        OMElement detail = fault.getFirstChildWithName(new QName("detail")).getFirstElement();
        String vrdResponseXML = detail.toString();
        throw new GeneralVRDException(vrdResponseXML, null); // need a better structure here..
    }
}