Example usage for javax.mail.internet MimeMultipart getBodyPart

List of usage examples for javax.mail.internet MimeMultipart getBodyPart

Introduction

In this page you can find the example usage for javax.mail.internet MimeMultipart getBodyPart.

Prototype

public synchronized BodyPart getBodyPart(String CID) throws MessagingException 

Source Link

Document

Get the MimeBodyPart referred to by the given ContentID (CID).

Usage

From source file:org.apache.james.transport.mailets.DSNBounceTest.java

@Test
public void serviceShouldAttachTheOriginalMailHeadersOnlyWhenAttachmentIsEqualToHeads() throws Exception {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME)
            .mailetContext(fakeMailContext).setProperty("attachment", "heads").build();
    dsnBounce.init(mailetConfig);//from   w  w  w . ja  va2  s. com

    MailAddress senderMailAddress = new MailAddress("sender@domain.com");
    FakeMail mail = FakeMail.builder().sender(senderMailAddress)
            .mimeMessage(MimeMessageBuilder.mimeMessageBuilder().setText("My content")
                    .addHeader("myHeader", "myValue").setSubject("mySubject"))
            .name(MAILET_NAME).recipient("recipient@domain.com")
            .lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z"))).build();

    dsnBounce.service(mail);

    List<SentMail> sentMails = fakeMailContext.getSentMails();
    assertThat(sentMails).hasSize(1);
    SentMail sentMail = sentMails.get(0);
    assertThat(sentMail.getSender()).isNull();
    assertThat(sentMail.getRecipients()).containsOnly(senderMailAddress);
    MimeMessage sentMessage = sentMail.getMsg();
    MimeMultipart content = (MimeMultipart) sentMessage.getContent();
    BodyPart bodyPart = content.getBodyPart(2);
    SharedByteArrayInputStream actualContent = (SharedByteArrayInputStream) bodyPart.getContent();
    assertThat(IOUtils.toString(actualContent, StandardCharsets.UTF_8)).contains("Subject: mySubject")
            .contains("myHeader: myValue");
    assertThat(bodyPart.getContentType()).isEqualTo("text/rfc822-headers; name=mySubject");
}

From source file:org.apache.james.transport.mailets.DSNBounceTest.java

@Test
public void serviceShouldSendMultipartMailContainingTextPart() throws Exception {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME)
            .mailetContext(fakeMailContext).build();
    dsnBounce.init(mailetConfig);/*from  w ww  . j av a 2s  . co m*/

    MailAddress senderMailAddress = new MailAddress("sender@domain.com");
    FakeMail mail = FakeMail.builder().sender(senderMailAddress).attribute("delivery-error", "Delivery error")
            .mimeMessage(MimeMessageBuilder.mimeMessageBuilder().setText("My content")).name(MAILET_NAME)
            .recipient("recipient@domain.com").lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z")))
            .build();

    dsnBounce.service(mail);

    String hostname = InetAddress.getLocalHost().getHostName();
    String expectedContent = "Hi. This is the James mail server at " + hostname
            + ".\nI'm afraid I wasn't able to deliver your message to the following addresses.\nThis is a permanent error; I've given up. Sorry it didn't work out.  Below\nI include the list of recipients and the reason why I was unable to deliver\nyour message.\n\n"
            + "Failed recipient(s):\n" + "recipient@domain.com\n" + "\n" + "Error message:\n"
            + "Delivery error\n" + "\n";

    List<SentMail> sentMails = fakeMailContext.getSentMails();
    assertThat(sentMails).hasSize(1);
    SentMail sentMail = sentMails.get(0);
    MimeMessage sentMessage = sentMail.getMsg();
    MimeMultipart content = (MimeMultipart) sentMessage.getContent();
    BodyPart bodyPart = content.getBodyPart(0);
    assertThat(bodyPart.getContentType()).isEqualTo("text/plain; charset=us-ascii");
    assertThat(bodyPart.getContent()).isEqualTo(expectedContent);
}

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);/*from   w  w  w  . j a va  2 s  . c o  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  w  w.ja va2s  .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(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:mitm.common.mail.filter.UnsupportedFormatStripper.java

private void scanPart(Part part, PartsContext context, int depth) throws MessagingException, IOException {
    if (depth > MAX_DEPTH) {
        return;/*from  w w  w .  ja va  2  s  .com*/
    }

    if (part.isMimeType("multipart/mixed")) {
        MimeMultipart parts = (MimeMultipart) part.getContent();

        int partCount = parts.getCount();

        for (int i = 0; i < partCount; i++) {
            Part child = parts.getBodyPart(i);

            scanPart(child, context, ++depth);
        }
    } else if (part.isMimeType("multipart/*")) {
        /*
         * We will always add any multipart that's not a mixed multipart
         */
        context.getParts().add(part);
    } else if (part.isMimeType("text/plain")) {
        context.getParts().add(part);
    } else if (part.isMimeType("text/html")) {
        context.getParts().add(part);
    } else if (!addSupportedPart(part, context)) {
        skipPart(part, true, context);
    }
}

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;/*w  w  w.ja  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.jahia.modules.gateway.mail.MailToJSONImpl.java

protected void parseMailMessage(Part part, MailContent content) throws IOException, MessagingException {
    Object mailContent = part.getContent();
    if (mailContent instanceof MimeMultipart) {
        MimeMultipart mailMessageContent = (MimeMultipart) mailContent;
        // We have some attachments
        for (int i = 0; i < mailMessageContent.getCount(); i++) {
            BodyPart bodyPart = mailMessageContent.getBodyPart(i);
            parseMailMessage(bodyPart, content);
        }// ww w. j  a v a 2s.c o m
    } else if (mailContent instanceof String && part.getDisposition() == null) {
        boolean isHtml = false;
        if (content.getBody() == null || ((isHtml = part.isMimeType("text/html")) && !content.isHtml())) {
            if (isHtml) {
                content.setBodyHtml((String) mailContent);
            } else {
                content.setBody((String) mailContent);
            }
        }
    } else if (mailContent instanceof InputStream || mailContent instanceof String) {
        File tempFile = File.createTempFile("mail2json-", null);
        try {
            FileUtils.copyInputStreamToFile(
                    mailContent instanceof InputStream ? (InputStream) mailContent : part.getInputStream(),
                    tempFile);
            content.getFiles()
                    .add(new FileItem(StringUtils.defaultIfEmpty(part.getFileName(), "unknown"), tempFile));
        } catch (IOException e) {
            FileUtils.deleteQuietly(tempFile);
            throw e;
        }
    }
    assert content.getBody() != 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   ww  w .j av  a  2  s. c  om

    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:io.lavagna.service.MailTicketService.java

private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException {
    String result = "";
    int count = mimeMultipart.getCount();
    for (int i = 0; i < count; i++) {
        BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.isMimeType("text/plain")) {
            result = result + "\n" + bodyPart.getContent();
            break;
        } else if (bodyPart.isMimeType("text/html")) {
            String html = (String) bodyPart.getContent();
            result = result + "\n" + Jsoup.parse(html).text();
        } else if (bodyPart.getContent() instanceof MimeMultipart) {
            result = result + getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent());
        }/*from  w  w w. j  av  a2s. c o m*/
    }
    return result;
}

From source file:org.sakaiproject.nakamura.smtp.SakaiSmtpServer.java

private void writeMultipartToNode(Session session, Content message, MimeMultipart multipart)
        throws MessagingException, AccessDeniedException, StorageClientException, IOException {
    int count = multipart.getCount();
    for (int i = 0; i < count; i++) {
        createChildNodeForPart(session, i, multipart.getBodyPart(i), message);
    }//from  ww w  .ja v a 2s  .  co m
}