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:com.example.securelogin.domain.service.mail.PasswordReissueMailSharedServiceImpl.java

@Override
public List<ReceivedMail> getReceivedMessages() {
    List<ReceivedMail> mails = new ArrayList<>();
    MimeMessage[] messages = greenMailBean.getReceivedMessages();
    for (MimeMessage message : messages) {
        ReceivedMail mail = new ReceivedMail();
        try {/*from   ww  w  . j  a v a2  s  . c  om*/
            mail.setTo(message.getFrom()[0].toString());
            mail.setFrom(message.getRecipients(Message.RecipientType.TO)[0].toString());
            mail.setSubject(message.getSubject());
            mail.setText(message.getContent().toString().replace("\r\n", ""));
            mails.add(mail);
        } catch (MessagingException e) {
            throw new SystemException(MessageKeys.E_SL_FW_9001, e);
        } catch (IOException e) {
            throw new SystemException(MessageKeys.E_SL_FW_9001, e);
        }

    }
    return mails;
}

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

@Test
public void testUnknownContentType() throws IOException, MessagingException {
    MimeMessage message = loadMessage("unknown-content-type.eml");

    Object content = message.getContent();

    // it seems that Javamail 1.4 returns a SharedByteArrayInputStream when
    // the message uses an unknown content type

    assertTrue(content instanceof SharedByteArrayInputStream);

    InputStream input = (SharedByteArrayInputStream) content;

    byte[] bytes = IOUtils.toByteArray(input);

    assertArrayEquals(MiscStringUtils.toAsciiBytes("body\r\n"), bytes);

    MailUtils.validateMessage(message);//from  w w w .  j ava 2s .  co m
}

From source file:com.silverpeas.mailinglist.service.notification.AdvancedNotificationHelperTest.java

protected void checkSimpleEmail(String address, String subject) throws Exception {
    Mailbox inbox = Mailbox.get(address);
    assertThat(inbox, is(notNullValue()));
    assertThat("No message for " + address, inbox.size(), is(1));
    MimeMessage alert = (MimeMessage) inbox.iterator().next();
    assertThat(alert, is(notNullValue()));
    assertThat(alert.getSubject(), is(subject));
    assertThat((String) alert.getContent(), is(textEmailContent));
}

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

@Test
public void testUnknownContentTypeMultipartAddPart() throws IOException, MessagingException {
    MimeMessage message = loadMessage("unknown-content-type-multipart.eml");

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

    BodyPart newPart = new MimeBodyPart();
    newPart.setContent("new part", "text/plain");

    multipart.addBodyPart(newPart);//  w  ww .  j  a  v  a 2 s. c om

    message.saveChanges();

    MailUtils.validateMessage(message);

    File file = new File("test/tmp/testunknowncontenttypemultipartaddpart.eml");

    MailUtils.writeMessage(message, file);
}

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);/*from   ww  w . j  a v a  2s  . com*/

    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  ww . ja  va  2 s.  c o  m*/

    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:org.cherchgk.test.ui.RestorePasswordUITest.java

@Test
public void testSuccessfulRestorePassword() throws MessagingException, IOException {
    openRestorePasswordPage();//from  w  ww.j a  va 2s .  c om
    restorePassword("test-user@example.com");
    $(Selectors.withText(RestorePasswordAction.SUCCESS_MESSAGE)).shouldBe(Condition.visible);
    assertEquals(1, mailServer.getReceivedMessages().length);
    MimeMessage message = mailServer.getReceivedMessages()[0];
    assertEquals("test-user@example.com", message.getAllRecipients()[0].toString());

    // ?, ? ??   ?,     ? ?  ?
    String text = message.getContent().toString();
    Matcher matcher = Pattern.compile(".*<a href=\"(.*)\">.*").matcher(text);
    assertTrue(matcher.find());
    String setNewPasswordPageUrl = matcher.group(1);
    open(setNewPasswordPageUrl);

    SelenideElement passwordField = $(By.name("password"));
    SelenideElement password2Field = $(By.name("password2"));
    SelenideElement setNewPasswordButton = $(By.id("set-new-password-button"));
    passwordField.shouldBe(Condition.visible);
    password2Field.shouldBe(Condition.visible);
    setNewPasswordButton.shouldBe(Condition.visible);

    passwordField.setValue("");
    password2Field.setValue("321");
    setNewPasswordButton.click();
    $(Selectors.withText(SetNewPasswordAction.PASSWORD_CANNOT_BE_EMPTY)).shouldBe(Condition.visible);

    passwordField.setValue("123");
    password2Field.setValue("321");
    setNewPasswordButton.click();
    $(Selectors.withText(SetNewPasswordAction.PASSWORDS_MUST_BE_EQUAL)).shouldBe(Condition.visible);

    passwordField.setValue("123");
    password2Field.setValue("123");
    setNewPasswordButton.click();
    $(Selectors.withText(SetNewPasswordAction.PASSWORD_SUCCESSFULLY_CHANGED)).shouldBe(Condition.visible);

    open(setNewPasswordPageUrl);
    $(Selectors.withText(ShowSetNewPasswordPageAction.TOKEN_IS_INVALID)).shouldBe(Condition.visible);
    $(By.name("password")).shouldBe(Condition.not(Condition.exist));
    $(By.name("password2")).shouldBe(Condition.not(Condition.exist));
    $(By.id("set-new-password-button")).shouldBe(Condition.not(Condition.exist));
}

From source file:com.silverpeas.mailinglist.model.TestMailingListComponent.java

protected void checkSimpleEmail(String address, String subject) throws Exception {
    Mailbox inbox = Mailbox.get(address);
    assertNotNull(inbox);/* w w w .j a v a  2  s .  c  o  m*/
    assertEquals("No message for " + address, 1, inbox.size());
    MimeMessage alert = (MimeMessage) inbox.iterator().next();
    assertNotNull(alert);
    assertEquals(subject, alert.getSubject());
    assertEquals("text/plain; charset=\"UTF-8\"", alert.getContentType());
    assertEquals(textEmailContent, (String) alert.getContent());
}

From source file:fi.foyt.fni.test.ui.base.gamelibrary.GameLibraryProposeGameTestsBase.java

@Test
@SqlSets("basic-users")
public void testPropose() throws Exception {
    if ("chrome".equals(getBrowser())) {
        // FIXME: File uploading fails with bad gateway on Sauce Labs when using Chrome.
        return;/*from w ww  .  j  av  a2 s . c  o  m*/
    }

    loginInternal("user@foyt.fi", "pass");
    navigate("/gamelibrary/proposegame/");

    File testPng = getTestPng();
    File testPdf = getTestPdf();

    waitAndSendKeys(".gamelibrary-propose-game-form-name", "My awesome game");
    waitAndSendKeys(".gamelibrary-propose-game-form-description", "This game is just pretty awesome");
    waitAndSendKeys(".gamelibrary-propose-game-form-authors-share", "5");

    waitAndSendKeys(".gamelibrary-propose-game-form-section-image input[name='file']",
            testPng.getAbsolutePath());
    waitForSelectorPresent(".gamelibrary-propose-game-form-section-image .upload-field-file-name");
    assertSelectorCount(".gamelibrary-propose-game-form-section-image .upload-field-file-name", 1);
    assertSelectorText(".gamelibrary-propose-game-form-section-image .upload-field-file-name",
            testPng.getName(), true, true);

    waitAndSendKeys(".gamelibrary-propose-game-form-section-downloadable input[name='file']",
            testPdf.getAbsolutePath());
    waitForSelectorPresent(".gamelibrary-propose-game-form-section-downloadable .upload-field-file-name");
    assertSelectorCount(".gamelibrary-propose-game-form-section-downloadable .upload-field-file-name", 1);
    assertSelectorText(".gamelibrary-propose-game-form-section-downloadable .upload-field-file-name",
            testPdf.getName(), true, true);

    waitAndSendKeys(".gamelibrary-propose-game-form-section-printable input[name='file']",
            testPdf.getAbsolutePath());
    waitForSelectorPresent(".gamelibrary-propose-game-form-section-printable .upload-field-file-name");
    assertSelectorCount(".gamelibrary-propose-game-form-section-printable .upload-field-file-name", 1);
    assertSelectorText(".gamelibrary-propose-game-form-section-printable .upload-field-file-name",
            testPdf.getName(), true, true);

    waitAndClick(".gamelibrary-propose-game-send");

    MimeMessage[] messages = getGreenMail().getReceivedMessages();
    assertEquals(2, messages.length);

    List<String> recipientAddressses = new ArrayList<>();

    for (MimeMessage message : messages) {
        assertEquals("New Publication into the Game Library", message.getSubject());
        assertTrue(StringUtils.contains((String) message.getContent(),
                "Test User (user@foyt.fi) has proposed that My awesome game"));
        Address[] recipients = message.getRecipients(RecipientType.TO);

        for (Address recipient : recipients) {
            String address = ((InternetAddress) recipient).getAddress();
            if (!recipientAddressses.contains(address)) {
                recipientAddressses.add(address);
            }
        }

    }

    assertEquals(Arrays.asList("librarian@foyt.fi", "admin@foyt.fi"), recipientAddressses);

    waitForSelectorVisible(".gamelibrary-publication h3 a");

    assertSelectorText(".gamelibrary-publication h3 a", "My awesome game", true, true);
    assertSelectorText(".gamelibrary-publication .gamelibrary-publication-description",
            "This game is just pretty awesome", true, true);

    executeSql(
            "update PublicationFile set contentType = 'DELETE' where id in (select printableFile_id from BookPublication where id in (select id from Publication where creator_id = ?) union select downloadableFile_id from BookPublication where id in (select id from Publication where creator_id = ?))",
            2, 2);
    executeSql("update Publication set defaultImage_id = null where creator_id = ?", 2);
    executeSql(
            "Update BookPublication set printableFile_id = null, downloadableFile_id = null where id in (select id from Publication where creator_id = ?)",
            2);
    executeSql(
            "delete from PublicationImage where publication_id in (select id from Publication where creator_id = ?)",
            2);
    executeSql("delete from PublicationFile where contentType = 'DELETE'");
    executeSql("delete from BookPublication where id in (select id from Publication where creator_id = ?)", 2);
    executeSql("delete from Publication where creator_id = ?", 2);
}

From source file:org.parancoe.test.LoggingMailSender.java

@Override
protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) {
    if (mimeMessages != null) {
        for (MimeMessage mimeMessage : mimeMessages) {
            try {
                logger.info("from: {}", (Object[]) mimeMessage.getFrom());
                logger.info("to: {}", (Object[]) mimeMessage.getRecipients(Message.RecipientType.TO));
                logger.info("cc: {}", (Object[]) mimeMessage.getRecipients(Message.RecipientType.CC));
                logger.info("bcc: {}", (Object[]) mimeMessage.getRecipients(Message.RecipientType.BCC));
                logger.info("subject: {}", mimeMessage.getSubject());
                logger.info("content: {}", mimeMessage.getContent().toString());
                logger.info("content type: {}", mimeMessage.getContentType());
            } catch (Exception ex) {
                logger.error("Can't get message content", ex);
            }//from www  . jav a  2 s.co m
        }
    }
}