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:org.sonar.server.notification.email.EmailNotificationChannelTest.java

@Test
public void shouldSendThreadedEmail() throws Exception {
    configure();/*from www.jav  a 2  s .c  o m*/
    EmailMessage emailMessage = new EmailMessage().setMessageId("reviews/view/1").setFrom("Full Username")
            .setTo("user@nowhere").setSubject("Review #3").setMessage("I'll take care of this violation.");
    underTest.deliver(emailMessage);

    List<WiserMessage> messages = smtpServer.getMessages();
    assertThat(messages).hasSize(1);

    MimeMessage email = messages.get(0).getMimeMessage();

    assertThat(email.getHeader("Content-Type", null)).isEqualTo("text/plain; charset=UTF-8");

    assertThat(email.getHeader("In-Reply-To", null)).isEqualTo("<reviews/view/1@nemo.sonarsource.org>");
    assertThat(email.getHeader("References", null)).isEqualTo("<reviews/view/1@nemo.sonarsource.org>");

    assertThat(email.getHeader("List-ID", null)).isEqualTo("SonarQube <sonar.nemo.sonarsource.org>");
    assertThat(email.getHeader("List-Archive", null)).isEqualTo("http://nemo.sonarsource.org");

    assertThat(email.getHeader("From", ",")).isEqualTo("\"Full Username (SonarQube)\" <server@nowhere>");
    assertThat(email.getHeader("To", null)).isEqualTo("<user@nowhere>");
    assertThat(email.getHeader("Subject", null)).isEqualTo("[SONARQUBE] Review #3");
    assertThat((String) email.getContent()).startsWith("I'll take care of this violation.");
}

From source file:org.sonar.server.notification.email.EmailNotificationChannelTest.java

@Test
public void shouldSendNonThreadedEmail() throws Exception {
    configure();/*from   w  w w.  j av  a 2 s .c  o m*/
    EmailMessage emailMessage = new EmailMessage().setTo("user@nowhere").setSubject("Foo").setMessage("Bar");
    underTest.deliver(emailMessage);

    List<WiserMessage> messages = smtpServer.getMessages();
    assertThat(messages).hasSize(1);

    MimeMessage email = messages.get(0).getMimeMessage();

    assertThat(email.getHeader("Content-Type", null)).isEqualTo("text/plain; charset=UTF-8");

    assertThat(email.getHeader("In-Reply-To", null)).isNull();
    assertThat(email.getHeader("References", null)).isNull();

    assertThat(email.getHeader("List-ID", null)).isEqualTo("SonarQube <sonar.nemo.sonarsource.org>");
    assertThat(email.getHeader("List-Archive", null)).isEqualTo("http://nemo.sonarsource.org");

    assertThat(email.getHeader("From", null)).isEqualTo("SonarQube <server@nowhere>");
    assertThat(email.getHeader("To", null)).isEqualTo("<user@nowhere>");
    assertThat(email.getHeader("Subject", null)).isEqualTo("[SONARQUBE] Foo");
    assertThat((String) email.getContent()).startsWith("Bar");
}

From source file:org.sonarqube.tests.issue.IssueNotificationsTest.java

@Test
public void notifications_for_personalized_emails() throws Exception {
    String version = RandomStringUtils.randomAlphanumeric(10);
    // 1st analysis without any issue (because no file is analyzed)
    createSampleProject(privateProject ? "private" : "public");
    createUsers();// w  w w. j a v a2s .c o m
    tester.settings().setGlobalSettings("sonar.issues.defaultAssigneeLogin", userWithUserRole.getLogin());

    runAnalysis("issue/xoo-with-scm", "sonar.projectVersion", version, "sonar.scm.provider", "xoo",
            "sonar.scm.disabled", "false", "sonar.exclusions", "**/*");

    // No email since all code is ignored
    waitUntilAllNotificationsAreDelivered(1);
    assertThat(smtpServer.getMessages()).isEmpty();

    // run 2nd analysis which will generate issues on the leak period
    runAnalysis("issue/xoo-with-scm", "sonar.projectVersion", version, "sonar.scm.provider", "xoo",
            "sonar.scm.disabled", "false");

    // We expect to receive a notification for each subscriber with UserRole.user
    // And a personalized email for the assignee userWithUserRole
    waitUntilAllNotificationsAreDelivered(privateProject ? 3 : 4);
    assertThat(smtpServer.getMessages()).hasSize(privateProject ? 3 : 4);

    // the last email sent is the personalized one
    MimeMessage message = smtpServer.getMessages().get(privateProject ? 2 : 3).getMimeMessage();

    assertThat(message.getHeader("To", null)).isEqualTo(format("<%s>", userWithUserRole.getEmail()));
    assertThat(message.getSubject()).contains("You have 13 new issues");
    assertThat((String) message.getContent()).contains("Project: Sample").contains("Version: " + version);
}

From source file:org.sonarqube.tests.issue.IssueNotificationsTest.java

void checkEmailSettings() throws Exception {
    // Send test email to the test user
    tester.wsClient().wsConnector().call(new PostRequest("api/emails/send").setParam("to", EMAIL_TEST)
            .setParam("message", "This is a test message from SonarQube")).failIfNotSuccessful();

    // We need to wait until all notifications will be delivered
    waitUntilAllNotificationsAreDelivered(1);

    assertThat(smtpServer.getMessages()).hasSize(1);

    MimeMessage message = smtpServer.getMessages().get(0).getMimeMessage();
    assertThat(message.getHeader("To", null)).isEqualTo("<" + EMAIL_TEST + ">");
    assertThat((String) message.getContent()).contains("This is a test message from SonarQube");
}

From source file:org.sonarqube.tests.settings.EmailsTest.java

@Test
public void send_test_email() throws Exception {
    updateEmailSettings("localhost", Integer.toString(SMTP_SERVER.getServer().getPort()), null, null, null,
            null, null, null);//from   w w w.  j a  v a  2  s  .c om

    sendEmail("test@example.org", "Test Message from SonarQube", "This is a test message from SonarQube");

    // We need to wait until all notifications will be delivered
    waitUntilAllNotificationsAreDelivered(1);
    Iterator<WiserMessage> emails = SMTP_SERVER.getMessages().iterator();
    MimeMessage message = emails.next().getMimeMessage();
    assertThat(Arrays.stream(message.getFrom()).map(Address::toString))
            .containsOnly("SonarQube <noreply@nowhere>");
    assertThat(message.getHeader("To", null)).isEqualTo("<test@example.org>");
    assertThat(message.getSubject()).isEqualTo("[SONARQUBE] Test Message from SonarQube");
    assertThat((String) message.getContent()).contains("This is a test message from SonarQube");
    assertThat(emails.hasNext()).isFalse();
}

From source file:org.sonarqube.tests.settings.EmailsTest.java

@Test
public void send_customized_test_email() throws Exception {
    String from = randomAlphanumeric(4) + "@" + randomAlphabetic(5);
    String fromName = randomAlphanumeric(5);
    String prefix = randomAlphanumeric(6);
    updateEmailSettings("localhost", Integer.toString(SMTP_SERVER.getServer().getPort()), from, fromName,
            prefix, null, null, null);// w  w  w.j  av  a2  s.c o  m

    sendEmail("test@example.org", "Test Message from SonarQube", "This is a test message from SonarQube");

    // We need to wait until all notifications will be delivered
    waitUntilAllNotificationsAreDelivered(1);
    Iterator<WiserMessage> emails = SMTP_SERVER.getMessages().iterator();
    MimeMessage message = emails.next().getMimeMessage();
    assertThat(Arrays.stream(message.getFrom()).map(Address::toString))
            .containsOnly(format("%s <%s>", fromName, from));
    assertThat(message.getHeader("To", null)).isEqualTo("<test@example.org>");
    assertThat(message.getSubject()).isEqualTo(prefix + " Test Message from SonarQube");
    assertThat((String) message.getContent()).contains("This is a test message from SonarQube");
    assertThat(emails.hasNext()).isFalse();
}

From source file:org.xwiki.administration.test.ui.ResetPasswordIT.java

protected Map<String, String> getMessageContent(MimeMessage message) throws Exception {
    Map<String, String> messageMap = new HashMap<String, String>();

    Address[] addresses = message.getAllRecipients();
    Assert.assertTrue(addresses.length == 1);
    messageMap.put("recipient", addresses[0].toString());

    messageMap.put("subjectLine", message.getSubject());

    Multipart mp = (Multipart) message.getContent();

    BodyPart plain = getPart(mp, "text/plain");
    if (plain != null) {
        messageMap.put("textPart", IOUtils.toString(plain.getInputStream()));
    }/*from w  w  w.ja v a  2s.com*/
    BodyPart html = getPart(mp, "text/html");
    if (html != null) {
        messageMap.put("htmlPart", IOUtils.toString(html.getInputStream()));
    }

    return messageMap;
}

From source file:org.xwiki.mail.internal.FileSystemMailContentStoreTest.java

@Test
public void loadMessage() throws Exception {
    String batchId = UUID.randomUUID().toString();
    String messageId = "ar1vm0Wca42E/dDn3dsH8ogs3/s=";
    String mimeMessageId = "<1128820400.0.1419205781342.JavaMail.contact@xwiki.org>";

    File tempDir = new File(TEMPORARY_DIRECTORY);
    File batchDirectory = new File(new File(tempDir, this.mocker.getComponentUnderTest().ROOT_DIRECTORY),
            URLEncoder.encode(batchId, "UTF-8"));
    batchDirectory.mkdirs();// w  w  w.  j av a2  s. c o  m
    File messageFile = new File(batchDirectory, URLEncoder.encode(messageId, "UTF-8"));
    messageFile.createNewFile();

    String newLine = System.getProperty("line.separator");

    FileWriter fileWriter = new FileWriter(messageFile, true);
    // Unique string is <hashcode>.<id>.<currentTime>.JavaMail.<suffix>
    fileWriter.append("Message-ID: " + mimeMessageId + newLine);
    fileWriter.append("MIME-Version: 1.0" + newLine);
    fileWriter.append("Content-Type: text/plain; charset=us-ascii" + newLine);
    fileWriter.append("Content-Transfer-Encoding: 7bit" + newLine + newLine);
    fileWriter.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit");
    fileWriter.close();

    Session session = Session.getInstance(new Properties());
    MimeMessage message = this.mocker.getComponentUnderTest().load(session, batchId, messageId);

    assertEquals(mimeMessageId, message.getMessageID());
    assertEquals("Lorem ipsum dolor sit amet, consectetur adipiscing elit", message.getContent());
}

From source file:org.xwiki.platform.notifications.test.ui.NotificationsTest.java

@Test
public void testNotificationsEmails() throws Exception {

    getUtil().login(SECOND_USER_NAME, SECOND_USER_PASSWORD);
    NotificationsUserProfilePage p;//w  ww. j a  v  a 2s. c  om
    p = NotificationsUserProfilePage.gotoPage(SECOND_USER_NAME);
    p.setPageCreatedEmail(true);

    getUtil().login(FIRST_USER_NAME, FIRST_USER_PASSWORD);
    DocumentReference page1 = new DocumentReference("xwiki", getTestClassName(), "Page1");
    DocumentReference page2 = new DocumentReference("xwiki", getTestClassName(), "Page2");

    getUtil().createPage(getTestClassName(), "Page1", "Content 1", "Title 1");
    getUtil().createPage(getTestClassName(), "Page2", "Content 2", "Title 2");

    // Trigger the notification email job
    getUtil().login(SUPERADMIN_USER_NAME, SUPERADMIN_PASSWORD);
    SchedulerHomePage schedulerHomePage = SchedulerHomePage.gotoPage();
    schedulerHomePage.clickJobActionTrigger("Notifications daily email");
    this.mail.waitForIncomingEmail(1);

    assertEquals(1, this.mail.getReceivedMessages().length);
    MimeMessage message = this.mail.getReceivedMessages()[0];
    assertTrue(message.getSubject().endsWith("event(s) on the wiki"));
    Multipart content = (Multipart) message.getContent();
    assertTrue(content.getContentType().startsWith("multipart/mixed;"));
    assertEquals(1, content.getCount());
    MimeBodyPart mimeBodyPart1 = (MimeBodyPart) content.getBodyPart(0);
    Multipart multipart1 = (Multipart) mimeBodyPart1.getContent();
    assertEquals(2, multipart1.getCount());
    assertEquals("text/plain; charset=UTF-8", multipart1.getBodyPart(0).getContentType());
    assertEquals("text/html; charset=UTF-8", multipart1.getBodyPart(1).getContentType());

    // Events inside an email comes in random order, so we just verify that all the expected content is there
    String email = prepareMail(multipart1.getBodyPart(0).getContent().toString());
    assertTrue(email
            .contains(prepareMail(IOUtils.toString(getClass().getResourceAsStream("/expectedMail1.txt")))));
    assertTrue(email
            .contains(prepareMail(IOUtils.toString(getClass().getResourceAsStream("/expectedMail2.txt")))));
    assertTrue(email
            .contains(prepareMail(IOUtils.toString(getClass().getResourceAsStream("/expectedMail3.txt")))));

    getUtil().rest().delete(page1);
    getUtil().rest().delete(page2);
}

From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java

public ShsMessage unmarshal(InputStream stream) throws IllegalMessageStructureException {
    log.trace("unmarshal(InputStream)");

    try {// w  w  w  .  j  av a  2 s . c  o m
        stream = SharedDeferredStream.toSharedInputStream(stream);
        MimeMessage mimeMessage = new MimeMessage(session, stream);
        Object msgContent = mimeMessage.getContent();

        if (!(msgContent instanceof MimeMultipart)) {
            throw new IllegalMessageStructureException(
                    "Expected a multipart mime message, got " + msgContent.getClass());
        }

        MimeMultipart multipart = (MimeMultipart) msgContent;

        if (multipart.getCount() < 2) {
            throw new IllegalMessageStructureException("SHS message must contain at least two mime bodyparts");
        }

        ShsMessage shsMessage = new ShsMessage();

        BodyPart labelPart = multipart.getBodyPart(0);
        if (!labelPart.isMimeType("text/xml") && !labelPart.isMimeType("text/plain")) {
            throw new IllegalMessageStructureException(
                    "First bodypart is not text/xml nor text/plain but was " + labelPart.getContentType());
        }

        ShsLabel label = shsLabelMarshaller.unmarshal((String) labelPart.getContent());

        shsMessage.setLabel(label);

        Content content = label.getContent();
        if (content == null) {
            throw new IllegalMessageStructureException("Label contains no content elements");
        }

        // this reads only as many mime body parts as there are content/data elements in the label
        int i = 1;
        for (Object o : content.getDataOrCompound()) {
            MimeBodyPart dp = (MimeBodyPart) multipart.getBodyPart(i);
            DataHandler dh = dp.getDataHandler();
            DataPart dataPart = new DataPart();
            dataPart.setDataHandler(new DataHandler(
                    new InputStreamDataSource(dh.getDataSource().getInputStream(), dh.getContentType())));

            dataPart.setContentType(dh.getContentType());

            String encoding = dp.getEncoding();
            if (encoding != null) {
                dataPart.setTransferEncoding(encoding);
            }

            dataPart.setFileName(dp.getFileName());

            if (o instanceof Data) {
                Data data = (Data) o;
                dataPart.setDataPartType(data.getDatapartType());
            } else if (o instanceof Compound) {
                continue;
            }
            shsMessage.addDataPart(dataPart);
            i++;
        }

        return shsMessage;

    } catch (Exception e) {
        if (e instanceof IllegalMessageStructureException) {
            throw (IllegalMessageStructureException) e;
        }

        throw new IllegalMessageStructureException(e);
    }
}