Example usage for javax.mail BodyPart getDataHandler

List of usage examples for javax.mail BodyPart getDataHandler

Introduction

In this page you can find the example usage for javax.mail BodyPart getDataHandler.

Prototype

public DataHandler getDataHandler() throws MessagingException;

Source Link

Document

Return a DataHandler for the content within this part.

Usage

From source file:MultipartViewer.java

protected Component getComponent(BodyPart bp) {

    try {//ww  w.j av  a2s .c o  m
        DataHandler dh = bp.getDataHandler();
        CommandInfo ci = dh.getCommand("view");
        if (ci == null) {
            throw new MessagingException("view command failed on: " + bp.getContentType());
        }

        Object bean = dh.getBean(ci);

        if (bean instanceof Component) {
            return (Component) bean;
        } else {
            if (bean == null)
                throw new MessagingException(
                        "bean is null, class " + ci.getCommandClass() + " , command " + ci.getCommandName());
            else
                throw new MessagingException("bean is not a awt.Component" + bean.getClass().toString());
        }
    } catch (MessagingException me) {
        return new Label(me.toString());
    }
}

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 w w.  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.apereo.portal.portlets.account.EmailPasswordResetNotificationImplTest.java

private String getBodyHtml(Multipart msg) throws Exception {
    for (int i = 0; i < msg.getCount(); i++) {
        BodyPart part = msg.getBodyPart(i);
        String type = part.getContentType();

        if ("text/plain".equals(type) || "text/html".equals(type)) {
            DataHandler handler = part.getDataHandler();
            String val = IOUtils.toString(handler.getInputStream());
            return val;
        }/*  ww w  . j  a va  2 s  . co m*/
    }

    return null;
}

From source file:org.drools.task.service.IcalBaseTest.java

public void testSendWithStartandEndDeadline() throws Exception {
    Map vars = new HashedMap();
    vars.put("users", users);
    vars.put("groups", groups);
    vars.put("now", new Date());

    String str = "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { createdOn = now, createdBy = users['tony'], activationTime = now}), ";
    str += "peopleAssignments = (with ( new PeopleAssignments() ) {potentialOwners = [users['steve' ], users['tony' ]]}), ";
    str += "names = [ new I18NText( 'en-UK', 'This is my task name')],";
    str += "subjects = [ new I18NText( 'en-UK', 'This is my task subject')],";
    str += "descriptions = [ new I18NText( 'en-UK', 'This is my task description')],";
    str += "deadlines = (with (new Deadlines() ) {";
    str += "    startDeadlines = [ ";
    str += "       (with (new Deadline()) {";
    str += "           date = now";
    str += "       } ) ],";
    str += "    endDeadlines = [";
    str += "        (with (new Deadline()) {";
    str += "             date = new Date( now.time + ( 1000 * 60 * 60 * 24 ) )"; // set to tomorrow
    str += "        } ) ]";
    str += "} ) })";

    MockUserInfo userInfo = new MockUserInfo();
    userInfo.getEmails().put(users.get("tony"), "tony@domain.com");
    userInfo.getEmails().put(users.get("steve"), "steve@domain.com");

    userInfo.getLanguages().put(users.get("tony"), "en-UK");
    userInfo.getLanguages().put(users.get("steve"), "en-UK");
    taskService.setUserinfo(userInfo);/*from  w w  w  .  jav  a  2s .  com*/

    BlockingAddTaskResponseHandler addTaskResponseHandler = new BlockingAddTaskResponseHandler();
    Task task = (Task) eval(new StringReader(str), vars);
    client.addTask(task, null, addTaskResponseHandler);

    long taskId = addTaskResponseHandler.getTaskId();

    BlockingTaskOperationResponseHandler responseHandler = new BlockingTaskOperationResponseHandler();
    client.claim(taskId, users.get("steve").getId(), responseHandler);
    responseHandler.waitTillDone(5000);

    assertEquals(2, getWiser().getMessages().size());

    assertEquals("steve@domain.com", getWiser().getMessages().get(0).getEnvelopeReceiver());
    assertEquals("steve@domain.com", getWiser().getMessages().get(1).getEnvelopeReceiver());

    String subject = "Summary\n-------\n\nThis is my task subject\n\n";
    String description = "Description\n-----------\n\nThis is my task description";

    MimeMessage msg = ((WiserMessage) getWiser().getMessages().get(0)).getMimeMessage();
    assertEqualsIgnoreWhitespace("multipart/alternative;boundary=\"----=_Part_", msg.getContentType(), 0, 47);
    assertEquals("tony@domain.com", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("tony@domain.com", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    assertEquals("steve@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[0]).getAddress());
    assertEquals("Task Assignment Start Event: This is my task name", msg.getSubject());

    MimeMultipart multiPart = (MimeMultipart) msg.getContent();

    BodyPart messageBodyPart = multiPart.getBodyPart(0);
    assertEquals("text/plain; charset=UTF8;", messageBodyPart.getDataHandler().getContentType());
    String content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(subject + description, content);

    messageBodyPart = multiPart.getBodyPart(1);
    assertEquals("text/calendar; charset=UTF8; name=ical-Start-1.ics",
            messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(
            "BEGIN:VCALENDARPRODID:-//iCal4j 1.0//ENCALSCALE:GREGORIANVERSION:2.0METHOD:REQUESTBEGIN:VEVENTDTSTART;TZID=UTC:",
            content.substring(0, 123));
    assertEqualsIgnoreWhitespace(
            "SUMMARY:\"Task Start : This is my task subject\"DESCRIPTION:\"This is my task description\"PRIORITY:55END:VEVENTEND:VCALENDAR",
            content.substring(content.length() - 131, content.length()));

    msg = ((WiserMessage) getWiser().getMessages().get(1)).getMimeMessage();
    assertEqualsIgnoreWhitespace("multipart/alternative;boundary=\"----=_Part_", msg.getContentType(), 0, 47);
    assertEquals("tony@domain.com", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("tony@domain.com", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    assertEquals("steve@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[0]).getAddress());
    assertEquals("Task Assignment End Event: This is my task name", msg.getSubject());

    multiPart = (MimeMultipart) msg.getContent();

    messageBodyPart = multiPart.getBodyPart(0);
    assertEquals("text/plain; charset=UTF8;", messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(subject + description, content);

    messageBodyPart = multiPart.getBodyPart(1);
    assertEquals("text/calendar; charset=UTF8; name=ical-End-1.ics",
            messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(
            "BEGIN:VCALENDARPRODID:-//iCal4j 1.0//ENCALSCALE:GREGORIANVERSION:2.0METHOD:REQUESTBEGIN:VEVENTDTSTART;TZID=UTC:",
            content.substring(0, 123));
    assertEqualsIgnoreWhitespace(
            "SUMMARY:\"Task End : This is my task subject\"DESCRIPTION:\"This is my task description\"PRIORITY:55END:VEVENTEND:VCALENDAR",
            content.substring(content.length() - 131, content.length()));
}

From source file:org.drools.task.service.IcalBaseTest.java

public void testSendWithStartDeadline() throws Exception {
    Map vars = new HashedMap();
    vars.put("users", users);
    vars.put("groups", groups);
    vars.put("now", new Date());

    String str = "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { createdOn = now, createdBy = users['tony'], activationTime = now}), ";
    str += "peopleAssignments = (with ( new PeopleAssignments() ) {potentialOwners = [users['steve' ], users['tony' ]]}), ";
    str += "names = [ new I18NText( 'en-UK', 'This is my task name')],";
    str += "subjects = [ new I18NText( 'en-UK', 'This is my task subject')],";
    str += "descriptions = [ new I18NText( 'en-UK', 'This is my task description')],";
    str += "deadlines = (with (new Deadlines() ) {";
    str += "    startDeadlines = [ ";
    str += "       (with (new Deadline()) {";
    str += "           date = now";
    str += "       } ) ]";
    str += "} ) })";

    MockUserInfo userInfo = new MockUserInfo();
    userInfo.getEmails().put(users.get("tony"), "tony@domain.com");
    userInfo.getEmails().put(users.get("steve"), "steve@domain.com");

    userInfo.getLanguages().put(users.get("tony"), "en-UK");
    userInfo.getLanguages().put(users.get("steve"), "en-UK");
    taskService.setUserinfo(userInfo);/*w w  w  .  j a v  a 2s . co  m*/

    BlockingAddTaskResponseHandler addTaskResponseHandler = new BlockingAddTaskResponseHandler();
    Task task = (Task) eval(new StringReader(str), vars);
    client.addTask(task, null, addTaskResponseHandler);

    long taskId = addTaskResponseHandler.getTaskId();

    BlockingTaskOperationResponseHandler responseHandler = new BlockingTaskOperationResponseHandler();
    client.claim(taskId, users.get("steve").getId(), responseHandler);
    responseHandler.waitTillDone(5000);

    assertEquals(1, getWiser().getMessages().size());

    assertEquals("steve@domain.com", getWiser().getMessages().get(0).getEnvelopeReceiver());

    String subject = "Summary\n-------\n\nThis is my task subject\n\n";
    String description = "Description\n-----------\n\nThis is my task description";

    MimeMessage msg = ((WiserMessage) getWiser().getMessages().get(0)).getMimeMessage();
    assertEqualsIgnoreWhitespace("multipart/alternative;boundary=\"----=_Part_", msg.getContentType(), 0, 47);
    assertEquals("tony@domain.com", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("tony@domain.com", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    assertEquals("steve@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[0]).getAddress());
    assertEquals("Task Assignment Start Event: This is my task name", msg.getSubject());

    MimeMultipart multiPart = (MimeMultipart) msg.getContent();

    BodyPart messageBodyPart = multiPart.getBodyPart(0);
    assertEquals("text/plain; charset=UTF8;", messageBodyPart.getDataHandler().getContentType());
    String content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(subject + description, content);

    messageBodyPart = multiPart.getBodyPart(1);
    assertEquals("text/calendar; charset=UTF8; name=ical-Start-1.ics",
            messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(
            "BEGIN:VCALENDARPRODID:-//iCal4j 1.0//ENCALSCALE:GREGORIANVERSION:2.0METHOD:REQUESTBEGIN:VEVENTDTSTART;TZID=UTC:",
            content.substring(0, 123));
    assertEqualsIgnoreWhitespace(
            "SUMMARY:\"Task Start : This is my task subject\"DESCRIPTION:\"This is my task description\"PRIORITY:55END:VEVENTEND:VCALENDAR",
            content.substring(content.length() - 131, content.length()));
}

From source file:org.drools.task.service.IcalBaseTest.java

public void testSendWithEndDeadline() throws Exception {
    Map vars = new HashedMap();
    vars.put("users", users);
    vars.put("groups", groups);
    vars.put("now", new Date());

    String str = "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { createdOn = now, createdBy = users['tony'], activationTime = now}), ";
    str += "peopleAssignments = (with ( new PeopleAssignments() ) {potentialOwners = [users['steve' ], users['tony' ]]}), ";
    str += "names = [ new I18NText( 'en-UK', 'This is my task name')],";
    str += "subjects = [ new I18NText( 'en-UK', 'This is my task subject')],";
    str += "descriptions = [ new I18NText( 'en-UK', 'This is my task description')],";
    str += "deadlines = (with (new Deadlines() ) {";
    str += "    endDeadlines = [";
    str += "        (with (new Deadline()) {";
    str += "             date = new Date( now.time + ( 1000 * 60 * 60 * 24 ) )"; // set to tomorrow
    str += "        } ) ]";
    str += "} ) })";

    MockUserInfo userInfo = new MockUserInfo();
    userInfo.getEmails().put(users.get("tony"), "tony@domain.com");
    userInfo.getEmails().put(users.get("steve"), "steve@domain.com");

    userInfo.getLanguages().put(users.get("tony"), "en-UK");
    userInfo.getLanguages().put(users.get("steve"), "en-UK");
    taskService.setUserinfo(userInfo);/*from w ww.  ja  v  a2 s. co  m*/

    BlockingAddTaskResponseHandler addTaskResponseHandler = new BlockingAddTaskResponseHandler();
    Task task = (Task) eval(new StringReader(str), vars);
    client.addTask(task, null, addTaskResponseHandler);

    long taskId = addTaskResponseHandler.getTaskId();

    BlockingTaskOperationResponseHandler responseHandler = new BlockingTaskOperationResponseHandler();
    client.claim(taskId, users.get("steve").getId(), responseHandler);

    responseHandler.waitTillDone(5000);

    assertEquals(1, getWiser().getMessages().size());

    assertEquals("steve@domain.com", getWiser().getMessages().get(0).getEnvelopeReceiver());

    String subject = "Summary\n-------\n\nThis is my task subject\n\n";
    String description = "Description\n-----------\n\nThis is my task description";

    MimeMessage msg = ((WiserMessage) getWiser().getMessages().get(0)).getMimeMessage();
    assertEqualsIgnoreWhitespace("multipart/alternative;boundary=\"----=_Part_", msg.getContentType(), 0, 47);
    assertEquals("tony@domain.com", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("tony@domain.com", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    assertEquals("steve@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[0]).getAddress());
    assertEquals("Task Assignment End Event: This is my task name", msg.getSubject());

    MimeMultipart multiPart = (MimeMultipart) msg.getContent();

    BodyPart messageBodyPart = multiPart.getBodyPart(0);
    assertEquals("text/plain; charset=UTF8;", messageBodyPart.getDataHandler().getContentType());
    String content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(subject + description, content);

    messageBodyPart = multiPart.getBodyPart(1);
    assertEquals("text/calendar; charset=UTF8; name=ical-End-1.ics",
            messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(
            "BEGIN:VCALENDARPRODID:-//iCal4j 1.0//ENCALSCALE:GREGORIANVERSION:2.0METHOD:REQUESTBEGIN:VEVENTDTSTART;TZID=UTC:",
            content.substring(0, 123));
    assertEqualsIgnoreWhitespace(
            "SUMMARY:\"Task End : This is my task subject\"DESCRIPTION:\"This is my task description\"PRIORITY:55END:VEVENTEND:VCALENDAR",
            content.substring(content.length() - 131, content.length()));
}

From source file:org.ikasan.component.endpoint.email.producer.EmailProducerTest.java

@Test
public void test_successful_email_withAttachment() throws MessagingException, IOException {

    EmailProducerConfiguration emailProducerConfiguration = getConfiguration(true, null);

    EmailProducer emailProducer = new EmailProducer();
    ((Configured) emailProducer).setConfiguration(emailProducerConfiguration);
    ((ManagedResource) emailProducer).startManagedResource();

    emailProducer.invoke(getEmailPayload(true, null));
    List<WiserMessage> messages = wiser.getMessages();

    Assert.assertTrue("Should be three messages - one per addressee", messages.size() == 3);
    for (WiserMessage message : wiser.getMessages()) {
        Assert.assertTrue("sender should be " + sender, sender.equals(message.getEnvelopeSender()));

        MimeMessage mimeMessage = message.getMimeMessage();
        MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();
        Assert.assertTrue("should be 2 bodypart", mimeMultipart.getCount() == 2);
        BodyPart bodyPart = mimeMultipart.getBodyPart(0);
        String content = (String) bodyPart.getContent();
        Assert.assertTrue("The email content should be empty", content.isEmpty());
        BodyPart attachment = mimeMultipart.getBodyPart(1);
        Assert.assertEquals("Check attachment file name", "testAttachment", attachment.getFileName());
        Assert.assertTrue("Check file content",
                IOUtils.toString(attachment.getDataHandler().getDataSource().getInputStream())
                        .contains("1997,Ford,E350"));
        Assert.assertTrue("Should find email format as \"text/plain\"",
                bodyPart.getContentType().contains("text/plain"));

    }/*from w w  w . j  a  v  a 2 s. c om*/
}

From source file:org.sourceforge.net.javamail4ews.transport.EwsTransport.java

private byte[] bodyPart2ByteArray(BodyPart pPart) throws IOException, MessagingException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    pPart.getDataHandler().writeTo(os);
    return os.toByteArray();
}