Example usage for javax.mail.internet MimeMessage getSubject

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

Introduction

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

Prototype

@Override
public String getSubject() throws MessagingException 

Source Link

Document

Returns the value of the "Subject" header field.

Usage

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);// ww w. j a  va2 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("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);//from   w  ww  . ja  v  a  2  s .co 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.springframework.integration.mail.AbstractMailReceiver.java

/**
 * Will filter Messages thru selector. Messages that did not pass selector filtering criteria
 * will be filtered out and remain on the server as never touched.
 *///ww w  . ja  v  a  2s . com
private Message[] filterMessagesThruSelector(Message[] messages) throws MessagingException {
    List<Message> filteredMessages = new LinkedList<Message>();
    for (int i = 0; i < messages.length; i++) {
        MimeMessage message = (MimeMessage) messages[i];
        if (this.selectorExpression != null) {
            if (this.selectorExpression.getValue(this.evaluationContext, message, Boolean.class)) {
                filteredMessages.add(message);
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Fetched email with subject '" + message.getSubject()
                            + "' will be discarded by the matching filter"
                            + " and will not be flagged as SEEN.");
                }
            }
        } else {
            filteredMessages.add(message);
        }
    }
    return filteredMessages.toArray(new Message[filteredMessages.size()]);
}

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

@Test
public void resetForgottenPassword() throws Exception {
    String userName = "testUser" + RandomStringUtils.randomAlphanumeric(6);
    String password = "password";
    String newPassword = "newPassword";

    // Create a user
    getUtil().createUser(userName, password, null);

    // Make sure we are not logged in and go to the reset password page
    getUtil().forceGuestUser();/*w ww.  java  2  s  .c om*/
    ResetPasswordPage resetPasswordPage = ResetPasswordPage.gotoPage();

    // Try to reset the password of a non existent user
    resetPasswordPage.setUserName("SomeUserThatDoesNotExist");
    resetPasswordPage.clickResetPassword();
    Assert.assertFalse(resetPasswordPage.isResetPasswordSent());
    Assert.assertTrue(resetPasswordPage.getMessage().contains("user does not exist"));

    // Try again
    resetPasswordPage = resetPasswordPage.clickRetry();

    // Try to reset the password of our user, when he has no email set
    resetPasswordPage.setUserName(userName);
    resetPasswordPage.clickResetPassword();
    Assert.assertFalse(resetPasswordPage.isResetPasswordSent());
    Assert.assertTrue(resetPasswordPage.getMessage().contains("email address not provided"));

    // Try again. This time, set the user's email address in the profile
    getUtil().loginAsSuperAdmin();
    getUtil().updateObject("XWiki", userName, "XWiki.XWikiUsers", 0, "email", "foo@bar.com", "form_token",
            getUtil().getSecretToken());
    getUtil().forceGuestUser();

    // Actually reset the user's password
    resetPasswordPage = ResetPasswordPage.gotoPage();
    resetPasswordPage.setUserName(userName);
    resetPasswordPage.clickResetPassword();

    // Check the result
    Assert.assertTrue(resetPasswordPage.isResetPasswordSent());
    // Check the emails received by the user
    MimeMessage[] receivedEmails = this.mail.getReceivedMessages();
    Assert.assertEquals(1, receivedEmails.length);
    MimeMessage receivedEmail = receivedEmails[0];
    Assert.assertEquals("Password reset request for " + userName, receivedEmail.getSubject());
    String receivedMailContent = getMessageContent(receivedEmail).get("textPart");
    String passwordResetLink = getResetLink(receivedMailContent, userName);
    Assert.assertNotNull(passwordResetLink);

    // Use the password reset link
    getUtil().gotoPage(passwordResetLink);
    // We should now be on the ResetPasswordComplete page
    ResetPasswordCompletePage resetPasswordCompletePage = new ResetPasswordCompletePage();
    // Check that the link was valid
    Assert.assertTrue(resetPasswordCompletePage.isResetLinkValid());
    resetPasswordCompletePage.setPassword(newPassword);
    resetPasswordCompletePage.setPasswordConfirmation(newPassword);
    resetPasswordCompletePage = resetPasswordCompletePage.clickSave();

    // Check the result
    Assert.assertTrue(resetPasswordCompletePage.isPasswordSuccessfullyReset());
    LoginPage loginPage = resetPasswordCompletePage.clickLogin();

    // Check the new password
    loginPage.loginAs(userName, newPassword);
    Assert.assertEquals(userName, getUtil().getLoggedInUserName());
}

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()));
    }//  w  w w  .  ja v a2  s  .  c  o  m
    BodyPart html = getPart(mp, "text/html");
    if (html != null) {
        messageMap.put("htmlPart", IOUtils.toString(html.getInputStream()));
    }

    return messageMap;
}

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.  jav  a2  s  .  co  m*/
    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:org.yes.cart.service.mail.impl.MailComposerImplTest.java

@Test
public void testComposeMimeMessageInternalFullIntegration()
        throws MessagingException, IOException, ClassNotFoundException {

    final MailTemplateResourcesProvider mailTemplateResourcesProvider = mockery
            .mock(MailTemplateResourcesProvider.class);

    mockery.checking(new Expectations() {
        {//from www  .java  2s .c  o m
            one(mailTemplateResourcesProvider).getTemplate(Arrays.asList("default/mail/"), "SHOP10", "en",
                    "imtest", ".txt");
            will(returnValue(IOUtils.toString(
                    new FileInputStream(new File("src/test/resources/mailtemplates/default/imtest/imtest.txt")),
                    "UTF-8")));
            one(mailTemplateResourcesProvider).getTemplate(Arrays.asList("default/mail/"), "SHOP10", "en",
                    "imtest", ".html");
            will(returnValue(IOUtils.toString(
                    new FileInputStream(
                            new File("src/test/resources/mailtemplates/default/imtest/imtest.html")),
                    "UTF-8")));
            one(mailTemplateResourcesProvider).getTemplate(Arrays.asList("default/mail/"), "SHOP10", "en",
                    "imtest", ".properties");
            will(returnValue(IOUtils.toString(
                    new FileInputStream(
                            new File("src/test/resources/mailtemplates/default/imtest/imtest.properties")),
                    "UTF-8")));
            one(mailTemplateResourcesProvider).getResource(Arrays.asList("default/mail/"), "SHOP10", "en",
                    "imtest", "test.gif");
            will(returnValue(IOUtils.toByteArray(new FileInputStream(
                    new File("src/test/resources/mailtemplates/default/imtest/resources/test.gif")))));
            one(mailTemplateResourcesProvider).getResource(Arrays.asList("default/mail/"), "SHOP10", "en",
                    "imtest", "test.jpeg");
            will(returnValue(IOUtils.toByteArray(new FileInputStream(
                    new File("src/test/resources/mailtemplates/default/imtest/resources/test.jpeg")))));
        }
    });

    // of course you would use DI in any real-world cases
    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    sender.setHost("localhost");
    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
    MailComposerImpl mailComposer = new MailComposerImpl(mailTemplateResourcesProvider);
    mailComposer.composeMessage(message, "SHOP10", "en", Arrays.asList("default/mail/"), "imtest",
            "test@localhost.lo", "to@somedomain.com", "cc@somedomain.com", "bcc@somedomain.com", createModel());
    assertTrue(helper.isMultipart());
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    helper.getMimeMessage().writeTo(byteArrayOutputStream);
    String str = byteArrayOutputStream.toString("UTF-8");
    assertNotNull(str);
    // html and text present in mail message
    assertTrue(str.contains("Bender lives in theme park with blackjack poetess"));
    assertTrue(str.contains("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>"));
    assertTrue(str.contains("From: test@localhost.lo"));
    assertTrue(str.contains("To: to@somedomain.com"));
    assertTrue(str.contains("cc@somedomain.com"));
    assertTrue(str.contains("Bcc: bcc@somedomain.com"));
    assertEquals(" ?", message.getSubject());

    mockery.assertIsSatisfied();
}

From source file:org.yes.cart.service.mail.impl.MailComposerImplTest.java

/**
 * html only/*from w w w .j a  va 2  s.c o  m*/
 */
@Test
public void testConvertMailEntityToMimeMessage()
        throws MessagingException, IOException, ClassNotFoundException {
    // of course you would use DI in any real-world cases

    final Mail mail = new MailEntity();
    mail.setShopCode("SHOP10");
    mail.setSubject(" ?");
    mail.setFrom("test@localhost.lo");
    mail.setRecipients("to@somedomain.com");
    mail.setCc("cc@somedomain.com");
    mail.setBcc("bcc@somedomain.com");
    mail.setTextVersion("Bender lives in theme park with blackjack poetess");
    mail.setHtmlVersion("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>");

    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    sender.setHost("localhost");
    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

    MailComposerImpl mailComposer = new MailComposerImpl(null);
    mailComposer.convertMessage(mail, message);

    assertTrue(helper.isMultipart());
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    helper.getMimeMessage().writeTo(byteArrayOutputStream);
    String str = byteArrayOutputStream.toString("UTF-8");
    assertNotNull(str);
    // html and text present in mail message
    assertTrue(str.contains("Bender lives in theme park with blackjack poetess"));
    assertTrue(str.contains("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>"));
    assertTrue(str.contains("From: test@localhost.lo"));
    assertTrue(str.contains("To: to@somedomain.com"));
    assertTrue(str.contains("cc@somedomain.com"));
    assertTrue(str.contains("Bcc: bcc@somedomain.com"));
    assertEquals(" ?", message.getSubject());

}