Example usage for javax.mail Message getContent

List of usage examples for javax.mail Message getContent

Introduction

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

Prototype

public Object getContent() throws IOException, MessagingException;

Source Link

Document

Return the content as a Java object.

Usage

From source file:org.usergrid.management.EmailFlowTest.java

@Test
public void testAppUserActivationResetpwdMail() throws Exception {

    ApplicationInfo appInfo = management.getApplicationInfo("test-organization/test-app");
    User user = setupAppUser(appInfo.getId(), "registration_requires_admin_approval", Boolean.TRUE,
            "testAppUserMailUrl", "testAppUserMailUrl@test.com", false);

    String subject = "Request For User Account Activation testAppUserMailUrl@test.com";
    String activation_url = String.format(properties.getProperty(PROPERTIES_USER_ACTIVATION_URL),
            "test-organization", "test-app", user.getUuid().toString());
    //Activation// w w  w .j av a2 s  .c  o m
    management.startAppUserActivationFlow(appInfo.getId(), user);

    List<Message> inbox = org.jvnet.mock_javamail.Mailbox.get("test@usergrid.com");
    assertFalse(inbox.isEmpty());
    MockImapClient client = new MockImapClient("usergrid.com", "test", "somepassword");
    client.processMail();

    // subject ok
    Message account_activation_message = inbox.get(0);
    assertEquals(subject, account_activation_message.getSubject());

    // activation url ok
    String mailContent = (String) ((MimeMultipart) account_activation_message.getContent()).getBodyPart(1)
            .getContent();
    logger.info(mailContent);
    assertTrue(StringUtils.contains(mailContent, activation_url));

    // token ok
    String token = getTokenFromMessage(account_activation_message);
    logger.info(token);
    ActivationState activeState = management.handleActivationTokenForAppUser(appInfo.getId(), user.getUuid(),
            token);
    assertEquals(ActivationState.ACTIVATED, activeState);

    subject = "Password Reset";
    String reset_url = String.format(properties.getProperty(PROPERTIES_USER_RESETPW_URL), "test-organization",
            "test-app", user.getUuid().toString());
    // reset_pwd
    management.startAppUserPasswordResetFlow(appInfo.getId(), user);

    inbox = org.jvnet.mock_javamail.Mailbox.get("testAppUserMailUrl@test.com");
    assertFalse(inbox.isEmpty());
    client = new MockImapClient("test.com", "testAppUserMailUrl", "somepassword");
    client.processMail();

    // subject ok
    Message password_reset_message = inbox.get(1);
    assertEquals(subject, password_reset_message.getSubject());

    // resetpwd url ok
    mailContent = (String) ((MimeMultipart) password_reset_message.getContent()).getBodyPart(1).getContent();
    logger.info(mailContent);
    assertTrue(StringUtils.contains(mailContent, reset_url));

    // token ok
    token = getTokenFromMessage(password_reset_message);
    logger.info(token);
    assertTrue(management.checkPasswordResetTokenForAppUser(appInfo.getId(), user.getUuid(), token));

    // ensure revoke works
    management.revokeAccessTokenForAppUser(token);
    assertFalse(management.checkPasswordResetTokenForAppUser(appInfo.getId(), user.getUuid(), token));
}

From source file:com.app.test.mail.DefaultMailSenderTest.java

@Test
public void testPopulatePaymentFailedMessage() throws Exception {
    _initializeVelocityTemplate(_clazz, _classInstance);

    Method populateMessage = _clazz.getDeclaredMethod("_populateMessage", String.class, String.class,
            String.class, Session.class);

    populateMessage.setAccessible(true);

    Message message = (Message) populateMessage.invoke(_classInstance, "user@test.com", "Payment Failed",
            "payment_failed_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Payment Failed", message.getSubject());
    Assert.assertEquals(_PAYMENT_FAILED_EMAIL, message.getContent());

    InternetAddress[] internetAddresses = new InternetAddress[1];

    internetAddresses[0] = new InternetAddress("user@test.com");

    Assert.assertArrayEquals(internetAddresses, message.getRecipients(Message.RecipientType.TO));
}

From source file:net.orpiske.dcd.collector.dataset.impl.MBoxDataSet.java

@Override
public Data next() {
    MBoxData mBoxData = null;/* w ww .ja  v  a 2s  . c om*/
    Message message;

    try {
        message = inbox.getMessage(currentMessage);

        if (logger.isDebugEnabled()) {
            logger.debug("Processing message " + currentMessage + " of " + messageCount + "");

            if (logger.isTraceEnabled()) {
                logger.trace("------- MESSAGE START -------");
                logger.trace(message.getContent().toString());
                logger.trace("-------  MESSAGE END  -------");
            }
        }

        mBoxData = new MBoxData(message.getContent().toString());
        mBoxData.setBody(message.getContent().toString());

        StringBuilder stringBuilder = new StringBuilder();
        Enumeration<Header> enumeration = message.getAllHeaders();
        while (enumeration.hasMoreElements()) {
            Header header = enumeration.nextElement();

            if (header.getName().equalsIgnoreCase("from")) {
                mBoxData.setOriginator(header.getValue());
            } else {
                stringBuilder.append(header.getValue());
            }

            if (header.getName().equalsIgnoreCase("date")) {
                String strDate = header.getValue();
                Date date = getDate(strDate);

                mBoxData.setDate(date);
            }

            stringBuilder.append('\n');
        }

        mBoxData.setHeader(stringBuilder.toString());
    } catch (MessagingException e) {
        logger.error("Unable to process message " + currentMessage + ": " + e.getMessage(), e);
    } catch (IOException e) {
        logger.error("I/O error while processing the message " + currentMessage + ": " + e.getMessage(), e);
    }

    currentMessage++;
    return mBoxData;
}

From source file:com.app.test.mail.DefaultMailSenderTest.java

@Test
public void testPopulateCardDetailsMessage() throws Exception {
    _initializeVelocityTemplate(_clazz, _classInstance);

    Method populateMessage = _clazz.getDeclaredMethod("_populateMessage", String.class, String.class,
            String.class, Session.class);

    populateMessage.setAccessible(true);

    Message message = (Message) populateMessage.invoke(_classInstance, "user@test.com", "Card Details Updated",
            "card_details_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Card Details Updated", message.getSubject());
    Assert.assertEquals(_CARD_DETAILS_EMAIL, message.getContent());

    InternetAddress[] internetAddresses = new InternetAddress[1];

    internetAddresses[0] = new InternetAddress("user@test.com");

    Assert.assertArrayEquals(internetAddresses, message.getRecipients(Message.RecipientType.TO));
}

From source file:com.app.test.mail.DefaultMailSenderTest.java

@Test
public void testPopulateResubscribeMessage() throws Exception {
    _initializeVelocityTemplate(_clazz, _classInstance);

    Method populateMessage = _clazz.getDeclaredMethod("_populateMessage", String.class, String.class,
            String.class, Session.class);

    populateMessage.setAccessible(true);

    Message message = (Message) populateMessage.invoke(_classInstance, "user@test.com",
            "Resubscribe Successful", "resubscribe_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Resubscribe Successful", message.getSubject());
    Assert.assertEquals(_RESUBSCRIBE_EMAIL, message.getContent());

    InternetAddress[] internetAddresses = new InternetAddress[1];

    internetAddresses[0] = new InternetAddress("user@test.com");

    Assert.assertArrayEquals(internetAddresses, message.getRecipients(Message.RecipientType.TO));
}

From source file:org.apache.usergrid.management.EmailFlowIT.java

@Test
public void testAppUserActivationResetpwdMail() throws Exception {
    String orgName = this.getClass().getName() + "1";
    String appName = name.getMethodName();
    String userName = "Test User";
    String email = "test-user-4@mockserver.com";
    String passwd = "testpassword";
    OrganizationOwnerInfo orgOwner;/*ww  w .  ja v a  2  s.  c  o  m*/

    orgOwner = createOwnerAndOrganization(orgName, appName, userName, email, passwd, false, false);
    assertNotNull(orgOwner);

    ApplicationInfo app = setup.getMgmtSvc().createApplication(orgOwner.getOrganization().getUuid(), appName);
    enableAdminApproval(app.getId());
    User user = setupAppUser(app.getId(), "testAppUserMailUrl", "testAppUserMailUrl@test.com", false);

    String subject = "Request For User Account Activation testAppUserMailUrl@test.com";
    String activation_url = String.format(setup.get(PROPERTIES_USER_ACTIVATION_URL), orgName, appName,
            user.getUuid().toString());

    // Activation
    setup.getMgmtSvc().startAppUserActivationFlow(app.getId(), user);

    List<Message> inbox = Mailbox.get(email);
    assertFalse(inbox.isEmpty());
    MockImapClient client = new MockImapClient("usergrid.com", "test", "somepassword");
    client.processMail();

    // subject ok
    Message activation = inbox.get(0);
    assertEquals(subject, activation.getSubject());

    // activation url ok
    String mailContent = (String) ((MimeMultipart) activation.getContent()).getBodyPart(1).getContent();
    LOG.info(mailContent);
    assertTrue(StringUtils.contains(mailContent, activation_url));

    // token ok
    String token = getTokenFromMessage(activation);
    LOG.info(token);
    ActivationState activeState = setup.getMgmtSvc().handleActivationTokenForAppUser(app.getId(),
            user.getUuid(), token);
    assertEquals(ActivationState.ACTIVATED, activeState);

    subject = "Password Reset";
    String reset_url = String.format(setup.get(PROPERTIES_USER_RESETPW_URL), orgName, appName,
            user.getUuid().toString());

    // reset_pwd
    setup.getMgmtSvc().startAppUserPasswordResetFlow(app.getId(), user);

    inbox = Mailbox.get("testAppUserMailUrl@test.com");
    assertFalse(inbox.isEmpty());
    client = new MockImapClient("test.com", "testAppUserMailUrl", "somepassword");
    client.processMail();

    // subject ok
    Message reset = inbox.get(1);
    assertEquals(subject, reset.getSubject());

    // resetpwd url ok
    mailContent = (String) ((MimeMultipart) reset.getContent()).getBodyPart(1).getContent();
    LOG.info(mailContent);
    assertTrue(StringUtils.contains(mailContent, reset_url));

    // token ok
    token = getTokenFromMessage(reset);
    LOG.info(token);
    assertTrue(setup.getMgmtSvc().checkPasswordResetTokenForAppUser(app.getId(), user.getUuid(), token));

    // ensure revoke works
    setup.getMgmtSvc().revokeAccessTokenForAppUser(token);
    assertFalse(setup.getMgmtSvc().checkPasswordResetTokenForAppUser(app.getId(), user.getUuid(), token));
}

From source file:net.fenyo.mail4hotspot.service.MailManager.java

public String getMessageContentString(final Message message) throws IOException, MessagingException {
    final Object content = message.getContent();
    if (String.class.isInstance(content))
        // content-type: text/{plain, html, etc.}
        // prfrer isMimeType(...)  getContentType().equals(...) car getContentType() peut contenir aussi le charset et renvoyer une string comme suit : << text/html; charset="us-ascii" >>
        if (message.isMimeType("text/html"))
            return GenericTools.html2Text((String) content);
        else if (message.isMimeType("text/plain"))
            return (String) content;
        else {//from  www .j ava  2 s . c  o m
            log.warn("message content-type not handled: " + message.getContentType()
                    + " -> downgrading to String");
            return (String) content;
        }
    else if (MimeMultipart.class.isInstance(content)) {
        boolean mixed = false;
        if (message.isMimeType("multipart/mixed"))
            mixed = true;
        else if (message.isMimeType("multipart/alternative"))
            mixed = false;
        else {
            log.warn("multipart content-type not handled: " + message.getContentType()
                    + " -> downgrading to multipart/mixed");
            mixed = true;
        }
        return getMultipartContentString((MimeMultipart) content, mixed);
    } else {
        log.warn("invalid message content type and class: " + content.getClass().toString() + " - "
                + message.getContentType());
        return "";
    }
}

From source file:com.app.test.mail.DefaultMailSenderTest.java

@Test
public void testPopulateCancellationMessage() throws Exception {
    _initializeVelocityTemplate(_clazz, _classInstance);

    Method populateMessage = _clazz.getDeclaredMethod("_populateMessage", String.class, String.class,
            String.class, Session.class);

    populateMessage.setAccessible(true);

    Message message = (Message) populateMessage.invoke(_classInstance, "user@test.com",
            "Cancellation Successful", "cancellation_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Cancellation Successful", message.getSubject());
    Assert.assertEquals(_CANCELLATION_EMAIL, message.getContent());

    InternetAddress[] internetAddresses = new InternetAddress[1];

    internetAddresses[0] = new InternetAddress("user@test.com");

    Assert.assertArrayEquals(internetAddresses, message.getRecipients(Message.RecipientType.TO));
}

From source file:org.apache.usergrid.rest.management.users.MUUserResourceIT.java

private String getTokenFromMessage(Message msg) throws IOException, MessagingException {
    String body = ((MimeMultipart) msg.getContent()).getBodyPart(0).getContent().toString();
    return StringUtils.substringAfterLast(body, "token=");
}

From source file:com.app.test.mail.DefaultMailSenderTest.java

@Test
public void testPopulateEmailMessage() throws Exception {
    _initializeVelocityTemplate(_clazz, _classInstance);

    Method populateEmailMessageMethod = _clazz.getDeclaredMethod("_populateEmailMessage", Map.class,
            String.class, String.class, Session.class);

    populateEmailMessageMethod.setAccessible(true);

    List<SearchResult> searchResults = new ArrayList<>();

    SearchQuery searchQuery = new SearchQuery(1, _USER_ID, "Test keywords");

    SearchResult searchResult = new SearchResult(1, "1234", "itemTitle", "$14.99", "$29.99",
            "http://www.ebay.com/itm/1234", "http://www.ebay.com/123.jpg");

    searchResults.add(searchResult);/* ww w . j a  va 2s.  c  om*/

    Map<SearchQuery, List<SearchResult>> searchQueryResultMap = new HashMap<>();

    searchQueryResultMap.put(searchQuery, searchResults);

    Message message = (Message) populateEmailMessageMethod.invoke(_classInstance, searchQueryResultMap,
            "user@test.com", "unsubscribeToken", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertTrue(message.getSubject().contains("New Search Results - "));
    Assert.assertEquals(_EMAIL_CONTENT, message.getContent());

    InternetAddress[] internetAddresses = new InternetAddress[1];

    internetAddresses[0] = new InternetAddress("user@test.com");

    Assert.assertArrayEquals(internetAddresses, message.getRecipients(Message.RecipientType.TO));
}