Example usage for javax.mail.internet MimeMessage getContent

List of usage examples for javax.mail.internet MimeMessage getContent

Introduction

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

Prototype

@Override
public Object getContent() throws IOException, MessagingException 

Source Link

Document

Return the content as a Java object.

Usage

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

@Test
public void testValidateMessageCorruptBase64() throws IOException, MessagingException {
    MimeMessage message = loadMessage("corrupt-base64.eml");

    /*/* w  ww.j a va 2 s. c  o  m*/
     * Saving the mssage used to fail with Javamail <= 1.4.3 but no longer fails with 1.4.4
     */
    message.saveChanges();

    MailUtils.validateMessage(message);

    try {
        message.getContent();

        fail();
    } catch (DecodingException e) {
        // expected
    }
}

From source file:mitm.common.security.smime.SMIMEEnvelopedInspectorImplTest.java

@Test
public void testOutlook2010MissingSubjKeyIdWorkAround() throws Exception {
    MimeMessage message = loadMessage("outlook2010_cert_missing_subjkeyid.eml");

    KeyStoreKeyProvider keyStoreKeyProvider = new KeyStoreKeyProvider(
            loadKeyStore(new File("test/resources/testdata/keys/outlook2010_cert_missing_subjkeyid.p12"), ""),
            "");/*from  w w  w  .j av  a  2 s  . c  om*/

    keyStoreKeyProvider.setUseOL2010Workaround(true);

    SMIMEEnvelopedInspector inspector = new SMIMEEnvelopedInspectorImpl(message, keyStoreKeyProvider,
            securityFactory.getNonSensitiveProvider(), securityFactory.getSensitiveProvider());

    MimeMessage decrypted = inspector.getContentAsMimeMessage();

    File file = new File(tempDir, "test-testOutlook2010MissingSubjKeyId-decrypted.eml");

    MailUtils.writeMessage(decrypted, file);

    assertNotNull(decrypted);
    assertTrue(decrypted.isMimeType("text/plain"));
    assertNull(decrypted.getSubject());
    assertEquals("Created with Outlook 2010 Beta (14.0.4536.1000)",
            StringUtils.trim((String) decrypted.getContent()));
}

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

@DirtiesContext
@Test//  ww  w. ja v  a2s.  c  o  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:com.haulmont.cuba.core.app.EmailerTest.java

private MimeBodyPart getFirstAttachment(MimeMessage msg) throws IOException, MessagingException {
    assertTrue(msg.getContent() instanceof MimeMultipart);
    MimeMultipart mimeMultipart = (MimeMultipart) msg.getContent();
    return (MimeBodyPart) mimeMultipart.getBodyPart(1);
}

From source file:it.ozimov.springboot.templating.mail.service.EmailServiceTest.java

@Test
public void sendMailWithTemplate()
        throws MessagingException, IOException, TemplateException, CannotSendEmailException {
    //Arrange// www .  jav  a  2s  . c o  m
    final Email email = getSimpleMail();
    assertThat(email.getSentAt(), is(nullValue()));
    final String toBeOverriddenBody = email.getBody();
    final String bodyToBeReturned = "Ciao Tito";
    when(templateService.mergeTemplateIntoString(any(String.class), any(Map.class)))
            .thenReturn(bodyToBeReturned);

    //Act
    final MimeMessage sentMessage = mailService.send(email, "never_called.ftl", Maps.newHashMap());

    //Assert
    assertThat(email.getSentAt(), not(is(nullValue())));
    validateFrom(email, sentMessage);
    validateReplyTo(email, sentMessage);
    validateTo(email, sentMessage);
    validateCc(email, sentMessage);
    validateBcc(email, sentMessage);
    validateSubject(email, sentMessage);
    assertThat(((MimeMultipart) sentMessage.getContent()).getBodyPart(0).getContent(),
            allOf(not(is(toBeOverriddenBody)), is(bodyToBeReturned)));

    verify(templateService, times(1)).mergeTemplateIntoString(any(String.class), any(Map.class));

    verify(javaMailSender, times(1)).createMimeMessage();
    verify(javaMailSender, times(1)).send(any(MimeMessage.class));
}

From source file:com.haulmont.cuba.core.app.EmailerTest.java

private MimeBodyPart getTextPart(MimeMessage msg) throws IOException, MessagingException {
    assertTrue(msg.getContent() instanceof MimeMultipart);
    MimeMultipart mimeMultipart = (MimeMultipart) msg.getContent();

    Object content2 = mimeMultipart.getBodyPart(0).getContent();
    assertTrue(content2 instanceof MimeMultipart);
    MimeMultipart textBodyPart = (MimeMultipart) content2;

    return (MimeBodyPart) textBodyPart.getBodyPart(0);
}

From source file:com.haulmont.cuba.core.app.EmailerTest.java

private MimeBodyPart getInlineAttachment(MimeMessage msg) throws IOException, MessagingException {
    assertTrue(msg.getContent() instanceof MimeMultipart);
    MimeMultipart mimeMultipart = (MimeMultipart) msg.getContent();

    Object content2 = mimeMultipart.getBodyPart(0).getContent();
    assertTrue(content2 instanceof MimeMultipart);
    MimeMultipart textBodyPart = (MimeMultipart) content2;

    return (MimeBodyPart) textBodyPart.getBodyPart(1);
}

From source file:de.contentreich.alfresco.repo.email.EMLTransformer.java

@Override
protected void transformInternal(ContentReader reader, ContentWriter writer, TransformationOptions options)
        throws Exception {
    // TikaInputStream tikaInputStream = null;
    try (InputStream is = reader.getContentInputStream()) {
        // wrap the given stream to a TikaInputStream instance
        // tikaInputStream =  TikaInputStream.get(reader.getContentInputStream());
        // final Icu4jEncodingDetector encodingDetector = new Icu4jEncodingDetector();
        // final Charset charset = encodingDetector.detect(tikaInputStream, new Metadata());

        // MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()), tikaInputStream);
        MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()), is);
        /*//  w w w  . j a  v  a 2 s.c o  m
        if (charset != null)
        {
        mimeMessage.setHeader("Content-Type", "text/plain; charset=" + charset.name());
        mimeMessage.setHeader("Content-Transfer-Encoding", "quoted-printable");
        }
        */
        final StringBuilder sb = new StringBuilder();
        Object content = mimeMessage.getContent();
        if (content instanceof Multipart) {
            boolean html = html();
            Map<String, String> parts = new HashMap<String, String>();
            processPreviewMultiPart((Multipart) content, parts);
            String part = getPreview(parts, html);
            if (part != null) {
                sb.append(part);
            }
            // sb.append(processPreviewMultiPart((Multipart) content));
        } else {
            sb.append(content.toString());
        }
        writer.putContent(sb.toString());
    }
    /* finally
    {
    if (tikaInputStream != null)
    {
        try
        {
            // it closes any other resources associated with it
            tikaInputStream.close();
        }
        catch (IOException e)
        {
            logger.error(e.getMessage(), e);
        }
    }
    } */
}

From source file:mitm.application.djigzo.relay.RelayHandler.java

private void extractMessageParts(MimeMessage message) throws MessagingException, IOException {
    /*/*from  ww w  . ja  va  2  s  .c  om*/
     * Fast fail. Only multipart mixed messages are supported. 
     */
    if (!message.isMimeType("multipart/mixed")) {
        return;
    }

    Multipart mp;

    try {
        mp = (Multipart) message.getContent();
    } catch (IOException e) {
        throw new MessagingException("Error getting message content.", e);
    }

    for (int i = 0; i < mp.getCount(); i++) {
        BodyPart part = mp.getBodyPart(i);

        if (part.isMimeType("message/rfc822")) {
            relayMessage = BodyPartUtils.extractFromRFC822(part);
        } else if (part.isMimeType("text/xml")) {
            metaPart = part;
        }

        if (metaPart != null && relayMessage != null) {
            break;
        }
    }
}

From source file:it.ozimov.springboot.templating.mail.service.EmailServiceTest.java

@Test
public void sendMailWithTemplateAndInlinePicture()
        throws MessagingException, IOException, TemplateException, CannotSendEmailException {
    //Arrange//from   www  .  j  a va 2  s  .co  m
    final Email email = getSimpleMail();
    assertThat(email.getSentAt(), is(nullValue()));
    final String toBeOverriddenBody = email.getBody();
    final String bodyToBeReturned = "<img src=\"100_percent_free.jpg\" />";
    final String imageName = "100_percent_free.jpg";

    when(templateService.mergeTemplateIntoString(any(String.class), any(Map.class)))
            .thenReturn(bodyToBeReturned);

    final File inlineImageFile = new File(
            getClass().getClassLoader().getResource("images" + File.separator + imageName).getFile());

    //Act
    final MimeMessage sentMessage = mailService.send(email, "never_called.ftl", Maps.newHashMap(),
            getInlinePicture(inlineImageFile, imageName));

    //Assert
    assertThat(email.getSentAt(), not(is(nullValue())));
    validateFrom(email, sentMessage);
    validateReplyTo(email, sentMessage);
    validateTo(email, sentMessage);
    validateCc(email, sentMessage);
    validateBcc(email, sentMessage);
    validateSubject(email, sentMessage);

    final String imageId = ((MimeBodyPart) (((MimeMultipart) sentMessage.getContent()).getBodyPart(0)))
            .getContentID();
    assertThat(((MimeMultipart) sentMessage.getContent()).getBodyPart(1).getContent(),
            allOf(not(is(toBeOverriddenBody)), not(is(bodyToBeReturned)),
                    is("<img src=\"cid:" + imageId.substring(1, imageId.length() - 1) + "\" />")));

    verify(templateService, times(1)).mergeTemplateIntoString(any(String.class), any(Map.class));
}