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.apache.nifi.processors.standard.TestPutEmail.java

@Test
public void testOutgoingMessage() throws Exception {
    // verifies that are set on the outgoing Message correctly
    runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
    runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
    runner.setProperty(PutEmail.FROM, "test@apache.org");
    runner.setProperty(PutEmail.MESSAGE, "Message Body");
    runner.setProperty(PutEmail.TO, "recipient@apache.org");

    runner.enqueue("Some Text".getBytes());

    runner.run();/*from   ww w.j av a 2  s  . com*/

    runner.assertQueueEmpty();
    runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);

    // Verify that the Message was populated correctly
    assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
    Message message = processor.getMessages().get(0);
    assertEquals("test@apache.org", message.getFrom()[0].toString());
    assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
    assertEquals("Message Body", message.getContent());
    assertEquals("recipient@apache.org", message.getRecipients(RecipientType.TO)[0].toString());
    assertNull(message.getRecipients(RecipientType.BCC));
    assertNull(message.getRecipients(RecipientType.CC));
}

From source file:com.intuit.tank.mail.TankMailer.java

private void logMsg(String host, Message m) {
    try {/*from   w  w w  .j av a2  s .co  m*/
        StringBuilder sb = new StringBuilder();
        sb.append("To: ").append(StringUtils.join(m.getAllRecipients(), ',')).append('\n');
        sb.append("From: ").append(StringUtils.join(m.getFrom(), ',')).append('\n');
        sb.append("Subject: ").append(m.getSubject()).append('\n');
        sb.append("Body: ").append(m.getContent()).append('\n');
        LOG.info("Sending email to server (" + host + "):\n" + sb.toString());
    } catch (Exception e) {
        LOG.error("Error generating log msg: " + e);
    }

}

From source file:org.apache.nifi.processors.standard.TestPutEmail.java

@Test
public void testOutgoingMessageWithOptionalProperties() throws Exception {
    // verifies that optional attributes are set on the outgoing Message correctly
    runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
    runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
    runner.setProperty(PutEmail.FROM, "${from}");
    runner.setProperty(PutEmail.MESSAGE, "${message}");
    runner.setProperty(PutEmail.TO, "${to}");
    runner.setProperty(PutEmail.BCC, "${bcc}");
    runner.setProperty(PutEmail.CC, "${cc}");

    Map<String, String> attributes = new HashMap<>();
    attributes.put("from", "test@apache.org <NiFi>");
    attributes.put("message", "the message body");
    attributes.put("to", "to@apache.org");
    attributes.put("bcc", "bcc@apache.org");
    attributes.put("cc", "cc@apache.org");
    runner.enqueue("Some Text".getBytes(), attributes);

    runner.run();//from  www  . j ava2s. com

    runner.assertQueueEmpty();
    runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);

    // Verify that the Message was populated correctly
    assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
    Message message = processor.getMessages().get(0);
    assertEquals("\"test@apache.org\" <NiFi>", message.getFrom()[0].toString());
    assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
    assertEquals("the message body", message.getContent());
    assertEquals(1, message.getRecipients(RecipientType.TO).length);
    assertEquals("to@apache.org", message.getRecipients(RecipientType.TO)[0].toString());
    assertEquals(1, message.getRecipients(RecipientType.BCC).length);
    assertEquals("bcc@apache.org", message.getRecipients(RecipientType.BCC)[0].toString());
    assertEquals(1, message.getRecipients(RecipientType.CC).length);
    assertEquals("cc@apache.org", message.getRecipients(RecipientType.CC)[0].toString());
}

From source file:org.biokoframework.http.scenario.ScenarioRunner.java

private String prettify(Message scenarioExecutionMessage) throws Exception {
    StringBuilder builder = new StringBuilder();
    builder.append("(\"").append(scenarioExecutionMessage.getSubject()).append("\" and \"")
            .append(escapeJava(scenarioExecutionMessage.getContent().toString())).append("\")");
    return builder.toString();
}

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

@Test
public void testPopulateWelcomeMessage() 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", "Welcome",
            "welcome_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Welcome", message.getSubject());
    Assert.assertEquals(_WELCOME_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:pt.lsts.neptus.comm.iridium.RockBlockIridiumMessenger.java

@Override
public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception {

    if (askGmailPassword || gmailPassword == null || gmailUsername == null) {
        Pair<String, String> credentials = GuiUtils.askCredentials(ConfigFetch.getSuperParentFrame(),
                "Enter Gmail Credentials", getGmailUsername(), getGmailPassword());
        if (credentials == null)
            return null;
        setGmailUsername(credentials.first());
        setGmailPassword(credentials.second());
        PluginUtils.saveProperties("conf/rockblock.props", this);
        askGmailPassword = false;//from  w  ww. j a  v  a2 s  .co m
    }

    Properties props = new Properties();
    props.put("mail.store.protocol", "imaps");
    ArrayList<IridiumMessage> messages = new ArrayList<>();
    try {
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword());

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        int numMsgs = inbox.getMessageCount();

        for (int i = numMsgs; i > 0; i--) {
            Message m = inbox.getMessage(i);
            if (m.getReceivedDate().before(timeSince)) {
                break;
            } else {
                MimeMultipart mime = (MimeMultipart) m.getContent();
                for (int j = 0; j < mime.getCount(); j++) {
                    BodyPart p = mime.getBodyPart(j);
                    Matcher matcher = pattern.matcher(p.getContentType());
                    if (matcher.matches()) {
                        InputStream stream = (InputStream) p.getContent();
                        byte[] data = IOUtils.toByteArray(stream);
                        IridiumMessage msg = process(data, matcher.group(1));
                        if (msg != null)
                            messages.add(msg);
                    }
                }
            }
        }
    } catch (NoSuchProviderException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (MessagingException ex) {
        ex.printStackTrace();
        System.exit(2);
    }

    return messages;
}

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

@Test
public void testAppUserConfirmationMail() throws Exception {

    ApplicationInfo appInfo = management.getApplicationInfo("test-organization/test-app");
    assertNotNull(appInfo);/*from   w  ww  .ja va 2s .  co m*/
    User user = setupAppUser(appInfo.getId(), "registration_requires_email_confirmation", Boolean.TRUE,
            "testAppUserConfMail", "testAppUserConfMail@test.com", true);

    String subject = "User Account Confirmation: testAppUserConfMail@test.com";
    String confirmation_url = String.format(properties.getProperty(PROPERTIES_USER_CONFIRMATION_URL),
            "test-organization", "test-app", user.getUuid().toString());
    // confirmation
    management.startAppUserActivationFlow(appInfo.getId(), user);

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

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

    // confirmation url ok
    String mailContent = (String) ((MimeMultipart) account_confirmation_message.getContent()).getBodyPart(1)
            .getContent();
    logger.info(mailContent);
    assertTrue(StringUtils.contains(mailContent, confirmation_url));

    // token ok
    String token = getTokenFromMessage(account_confirmation_message);
    logger.info(token);
    ActivationState activeState = management.handleConfirmationTokenForAppUser(appInfo.getId(), user.getUuid(),
            token);
    assertEquals(ActivationState.CONFIRMED_AWAITING_ACTIVATION, activeState);

}

From source file:org.apache.nifi.processors.standard.TestPutEmail.java

@Test
public void testOutgoingMessageAttachment() throws Exception {
    // verifies that are set on the outgoing Message correctly
    runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
    runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
    runner.setProperty(PutEmail.FROM, "test@apache.org");
    runner.setProperty(PutEmail.MESSAGE, "Message Body");
    runner.setProperty(PutEmail.ATTACH_FILE, "true");
    runner.setProperty(PutEmail.CONTENT_TYPE, "text/html");
    runner.setProperty(PutEmail.TO, "recipient@apache.org");

    runner.enqueue("Some text".getBytes());

    runner.run();/* w  ww.  j  a va  2  s  .  c  om*/

    runner.assertQueueEmpty();
    runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);

    // Verify that the Message was populated correctly
    assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
    Message message = processor.getMessages().get(0);
    assertEquals("test@apache.org", message.getFrom()[0].toString());
    assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
    assertEquals("recipient@apache.org", message.getRecipients(RecipientType.TO)[0].toString());

    assertTrue(message.getContent() instanceof MimeMultipart);

    final MimeMultipart multipart = (MimeMultipart) message.getContent();
    final BodyPart part = multipart.getBodyPart(0);
    final InputStream is = part.getDataHandler().getInputStream();
    final String decodedText = StringUtils.newStringUtf8(Base64.decodeBase64(IOUtils.toString(is, "UTF-8")));
    assertEquals("Message Body", decodedText);

    final BodyPart attachPart = multipart.getBodyPart(1);
    final InputStream attachIs = attachPart.getDataHandler().getInputStream();
    final String text = IOUtils.toString(attachIs, "UTF-8");
    assertEquals("Some text", text);

    assertNull(message.getRecipients(RecipientType.BCC));
    assertNull(message.getRecipients(RecipientType.CC));
}

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

/** Tests to make sure a normal user must be activated by the admin after confirmation. */
@Test/* w ww  .  j a v  a 2s.c  o m*/
public void testAppUserConfirmationMail() throws Exception {
    String orgName = this.getClass().getName();
    String appName = name.getMethodName();
    String userName = "Test User";
    String email = "test-user-45@mockserver.com";
    String passwd = "testpassword";
    OrganizationOwnerInfo orgOwner;

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

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

    String subject = "User Account Confirmation: testAppUserConfMail@test.com";
    String urlProp = setup.get(PROPERTIES_USER_CONFIRMATION_URL);
    String confirmation_url = String.format(urlProp, orgName, appName, user.getUuid().toString());

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

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

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

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

    // token ok
    String token = getTokenFromMessage(confirmation);
    LOG.info(token);
    ActivationState activeState = setup.getMgmtSvc().handleConfirmationTokenForAppUser(app.getId(),
            user.getUuid(), token);
    assertEquals(ActivationState.CONFIRMED_AWAITING_ACTIVATION, activeState);
}

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

@Test
public void testPopulateContactMessage() throws Exception {
    Method populateContactMessage = _clazz.getDeclaredMethod("_populateContactMessage", String.class,
            String.class, Session.class);

    populateContactMessage.setAccessible(true);

    Message message = (Message) populateContactMessage.invoke(_classInstance, "user@test.com",
            "Sample contact message", _session);

    Assert.assertEquals("user@test.com", message.getFrom()[0].toString());
    Assert.assertEquals("You Have A New Message From user@test.com", message.getSubject());
    Assert.assertEquals("Sample contact message", message.getContent());
}