Java Code Examples for javax.mail.internet.MimeMultipart#getBodyPart()

The following examples show how to use javax.mail.internet.MimeMultipart#getBodyPart() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NntpUtil.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private static String getBodyPart(MimeMultipart mimeMultiPart) throws IOException, MessagingException
{
	for(int i=0; i<mimeMultiPart.getCount(); i++)
	{
		BodyPart bodyPart = mimeMultiPart.getBodyPart(i); 
		if(bodyPart.isMimeType("text/plain"))
		{
			return (String) bodyPart.getContent();
		}
		else if(bodyPart.getContent() instanceof MimeMultipart)
		{
			return getBodyPart((MimeMultipart)bodyPart.getContent());
		}
	}
	return "";
}
 
Example 2
Source File: MailReceiverUtils.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
private String getTextFromMimeMultipart(MimeMultipart mimeMultipart)
    throws MessagingException, IOException {
  StringBuilder result = new StringBuilder();
  int count = mimeMultipart.getCount();
  for (int i = 0; i < count; i++) {
    BodyPart bodyPart = mimeMultipart.getBodyPart(i);
    if (bodyPart.isMimeType("text/plain")) {
      result.append("\n").append(bodyPart.getContent());
    } else if (bodyPart.isMimeType("text/html")) {
      result.append("\n").append((String) bodyPart.getContent());
    } else if (bodyPart.getContent() instanceof MimeMultipart) {
      result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
    }
  }
  return result.toString();
}
 
Example 3
Source File: LargeMessageTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve message from retriever and check the attachment and text content
 *
 * @param server Server to read from
 * @param to     Account to retrieve
 */
private void retrieveAndCheck(AbstractServer server, String to) throws MessagingException, IOException {
    try (Retriever retriever = new Retriever(server)) {
        Message[] messages = retriever.getMessages(to);
        assertEquals(1, messages.length);
        Message message = messages[0];
        assertTrue(message.getContentType().startsWith("multipart/mixed"));
        MimeMultipart body = (MimeMultipart) message.getContent();
        assertTrue(body.getContentType().startsWith("multipart/mixed"));
        assertEquals(2, body.getCount());

        // Message text
        final BodyPart textPart = body.getBodyPart(0);
        String text = (String) textPart.getContent();
        assertEquals(createLargeString(), text);

        final BodyPart attachment = body.getBodyPart(1);
        assertTrue(attachment.getContentType().equalsIgnoreCase("application/blubb; name=file"));
        InputStream attachmentStream = (InputStream) attachment.getContent();
        byte[] bytes = IOUtils.toByteArray(attachmentStream);
        assertArrayEquals(createLargeByteArray(), bytes);
    }
}
 
Example 4
Source File: EmailNotificationTest.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void forThreepidInvite() throws MessagingException, IOException {
    String registerUrl = "https://" + RandomStringUtils.randomAlphanumeric(20) + ".example.org/register";
    gm.setUser(user, user);

    _MatrixID sender = MatrixID.asAcceptable(user, domain);
    ThreePidInvite inv = new ThreePidInvite(sender, ThreePidMedium.Email.getId(), target, "!rid:" + domain);
    inv.getProperties().put(PlaceholderNotificationGenerator.RegisterUrl, registerUrl);
    m.getNotif().sendForReply(new ThreePidInviteReply("a", inv, "b", "c", new ArrayList<>()));

    assertEquals(1, gm.getReceivedMessages().length);
    MimeMessage msg = gm.getReceivedMessages()[0];
    assertEquals(1, msg.getFrom().length);
    assertEquals(senderNameEncoded, msg.getFrom()[0].toString());
    assertEquals(1, msg.getRecipients(Message.RecipientType.TO).length);

    // We just check on the text/plain one. HTML is multipart and it's difficult so we skip
    MimeMultipart content = (MimeMultipart) msg.getContent();
    MimeBodyPart mbp = (MimeBodyPart) content.getBodyPart(0);
    String mbpContent = mbp.getContent().toString();
    assertTrue(mbpContent.contains(registerUrl));
}
 
Example 5
Source File: MailerImplTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private String getInlineAttachment(String cid, MimeMultipart multipart) throws IOException, MessagingException {
    for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        if (bodyPart.getContent() instanceof MimeMultipart) {
            for (int j = 0; j < ((MimeMultipart) bodyPart.getContent()).getCount(); j++) {
                BodyPart nested = ((MimeMultipart) bodyPart.getContent()).getBodyPart(j);
                if (nested.getHeader("Content-ID") != null && nested.getHeader("Content-ID")[0].equalsIgnoreCase(cid)) {
                    assertThat(nested.getDisposition()).isEqualTo("inline");
                    assertThat(nested.getContentType()).startsWith(TEXT_CONTENT_TYPE);
                    return read(nested);
                }
            }
        }
    }
    return null;
}
 
Example 6
Source File: DSNBounceTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void serviceShouldAttachTheOriginalMailHeadersOnlyWhenAttachmentIsEqualToHeads() throws Exception {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
            .mailetName(MAILET_NAME)
            .mailetContext(fakeMailContext)
            .setProperty("attachment", "heads")
            .build();
    dsnBounce.init(mailetConfig);

    MailAddress senderMailAddress = new MailAddress("[email protected]");
    FakeMail mail = FakeMail.builder()
            .name(MAILET_NAME)
            .sender(senderMailAddress)
            .mimeMessage(MimeMessageBuilder.mimeMessageBuilder()
                .setText("My content")
                .addHeader("myHeader", "myValue")
                .setSubject("mySubject"))
            .recipient("[email protected]")
            .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");
}
 
Example 7
Source File: MailerImplTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private List<String> getContentTypesFromMimeMultipart(
        MimeMultipart mimeMultipart) throws MessagingException, IOException {
    List<String> types = new ArrayList<>();
    int count = mimeMultipart.getCount();
    for (int i = 0; i < count; i++) {
        BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.getContent() instanceof MimeMultipart) {
            types.addAll(getContentTypesFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
        } else {
            types.add(bodyPart.getContentType());
        }
    }
    return types;
}
 
Example 8
Source File: MailHandlerServlet.java    From flickr-uploader with GNU General Public License v2.0 5 votes vote down vote up
private void print(MimeMessage message) throws MessagingException, IOException {
	logger.debug("subject:" + message.getSubject());
	logger.debug("description:" + message.getDescription());
	logger.debug("contentType:" + message.getContentType());
	logger.debug("sender:" + message.getSender());
	logger.debug("from:" + Arrays.toString(message.getFrom()));
	logger.debug("recipient:" + Arrays.toString(message.getAllRecipients()));
	// logger.debug("description:"+message.);
	// Enumeration allHeaderLines = message.getAllHeaderLines();
	// while (allHeaderLines.hasMoreElements()) {
	// logger.debug("allHeaderLines:"+allHeaderLines.nextElement());
	// }
	logger.debug("content:" + message.getContent());
	logger.debug("content:" + message.getContent().getClass());
	Multipart mp = (Multipart) message.getContent();
	logger.debug("count:" + mp.getCount());
	for (int i = 0; i < mp.getCount(); i++) {
		MimeBodyPart bodyPart = (MimeBodyPart) mp.getBodyPart(i);
		logger.debug("bodyPart content type:" + bodyPart.getContentType());
		logger.debug("bodyPart content:" + bodyPart.getContent().getClass());
		logger.debug("bodyPart content:" + bodyPart.getContent());
		if (bodyPart.getContent() instanceof MimeMultipart) {
			MimeMultipart mimeMultipart = (MimeMultipart) bodyPart.getContent();
			for (int j = 0; j < mimeMultipart.getCount(); j++) {
				BodyPart part = mimeMultipart.getBodyPart(j);
				logger.debug(i + " - bodyPart content type:" + part.getContentType());
				logger.debug(i + " - bodyPart content:" + part.getContent().getClass());
				logger.debug(i + " - bodyPart content:" + part.getContent());
			}
		}
	}
}
 
Example 9
Source File: Pop3Util.java    From anyline with Apache License 2.0 5 votes vote down vote up
/** 
 * 判断邮件中是否包含附件 
 *  
 * @param part part 
 * @return 邮件中存在附件返回true,不存在返回false 
 * @throws MessagingException MessagingException
 * @throws IOException IOException
 * @return boolean
 */
public static boolean isContainAttachment(Part part)  throws MessagingException, IOException { 
	boolean flag = false; 
	if (part.isMimeType("multipart/*")) { 
		MimeMultipart multipart = (MimeMultipart) part.getContent(); 
		int partCount = multipart.getCount(); 
		for (int i = 0; i < partCount; i++) { 
			BodyPart bodyPart = multipart.getBodyPart(i); 
			String disp = bodyPart.getDisposition(); 
			if (disp != null 
					&& (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp 
							.equalsIgnoreCase(Part.INLINE))) { 
				flag = true; 
			} else if (bodyPart.isMimeType("multipart/*")) { 
				flag = isContainAttachment(bodyPart); 
			} else { 
				String contentType = bodyPart.getContentType(); 
				if (contentType.indexOf("application") != -1) { 
					flag = true; 
				} 

				if (contentType.indexOf("name") != -1) { 
					flag = true; 
				} 
			} 

			if (flag) 
				break; 
		} 
	} else if (part.isMimeType("message/rfc822")) { 
		flag = isContainAttachment((Part) part.getContent()); 
	} 
	return flag; 
}
 
Example 10
Source File: SmtpServerTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testSmtpServerReceiveMultipart() throws Exception {
    assertEquals(0, greenMail.getReceivedMessages().length);

    String subject = GreenMailUtil.random();
    String body = GreenMailUtil.random();
    GreenMailUtil.sendAttachmentEmail("[email protected]", "[email protected]", subject, body, new byte[]{0, 1, 2}, "image/gif", "testimage_filename", "testimage_description", ServerSetupTest.SMTP);
    greenMail.waitForIncomingEmail(1500, 1);
    Message[] emails = greenMail.getReceivedMessages();
    assertEquals(1, emails.length);
    assertEquals(subject, emails[0].getSubject());

    Object o = emails[0].getContent();
    assertTrue(o instanceof MimeMultipart);
    MimeMultipart mp = (MimeMultipart) o;
    assertEquals(2, mp.getCount());
    BodyPart bp;
    bp = mp.getBodyPart(0);
    assertEquals(body, GreenMailUtil.getBody(bp).trim());

    bp = mp.getBodyPart(1);
    assertEquals("AAEC", GreenMailUtil.getBody(bp).trim());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    GreenMailUtil.copyStream(bp.getInputStream(), bout);
    byte[] gif = bout.toByteArray();
    for (int i = 0; i < gif.length; i++) {
        assertEquals(i, gif[i]);
    }
}
 
Example 11
Source File: MessageToCoreToMessage.java    From james-project with Apache License 2.0 5 votes vote down vote up
protected static String getScript(MimeMessage message) throws IOException, MessagingException {
    String result = null;
    if (message.getContentType().startsWith("multipart/")) {
        MimeMultipart parts = (MimeMultipart) message.getContent();
        boolean found = false;
        // Find the first part with any of:
        // - an attachment type of "application/sieve"
        // - a file suffix of ".siv"
        // - a file suffix of ".sieve"
        for (int i = 0; !found && i < parts.getCount(); i++) {
            MimeBodyPart part = (MimeBodyPart) parts.getBodyPart(i);
            found = part.isMimeType("application/sieve");
            if (!found) {
                String fileName = null == part.getFileName() ? null : part.getFileName().toLowerCase(Locale.US);
                found = fileName != null &&
                    (fileName.endsWith(".siv") || fileName.endsWith(".sieve"));
            }
            if (found) {
                Object content = part.getContent();
                if (content instanceof String) {
                    return (String) part.getContent();
                }
                InputStream is = (InputStream) part.getContent();
                try (Scanner scanner = new Scanner(is, "UTF-8")) {
                    scanner.useDelimiter("\\A");
                    if (scanner.hasNext()) {
                        result = scanner.next();
                    }
                }
            }
        }
    }
    if (null == result) {
        throw new MessagingException("Script part not found in this message");
    }
    return result;
}
 
Example 12
Source File: MailUtils.java    From scada with MIT License 5 votes vote down vote up
/**
 * �ж��ʼ����Ƿ��������
 * @param msg �ʼ�����
 * @return �ʼ��д��ڸ�������true�������ڷ���false
 */ 
public static boolean isContainAttachment(Part part) throws MessagingException, IOException { 
    boolean flag = false; 
    if (part.isMimeType("multipart/*")) { 
        MimeMultipart multipart = (MimeMultipart) part.getContent(); 
        int partCount = multipart.getCount(); 
        for (int i = 0; i < partCount; i++) { 
            BodyPart bodyPart = multipart.getBodyPart(i); 
            String disp = bodyPart.getDisposition(); 
            if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { 
                flag = true; 
            } else if (bodyPart.isMimeType("multipart/*")) { 
                flag = isContainAttachment(bodyPart); 
            } else { 
                String contentType = bodyPart.getContentType(); 
                if (contentType.indexOf("application") != -1) { 
                    flag = true; 
                }   
                 
                if (contentType.indexOf("name") != -1) { 
                    flag = true; 
                }  
            } 
             
            if (flag) break; 
        } 
    } else if (part.isMimeType("message/rfc822")) { 
        flag = isContainAttachment((Part)part.getContent()); 
    } 
    return flag; 
}
 
Example 13
Source File: EmailerTest.java    From cuba with Apache License 2.0 5 votes vote down vote up
private MimeBodyPart getTextPart(MimeMessage msg) throws IOException, MessagingException {
    assertTrue(msg.getContent() instanceof MimeMultipart);
    MimeMultipart mimeMultipart = (MimeMultipart) msg.getContent();

    Object content2 = mimeMultipart.getBodyPart(0).getContent();
    assertTrue(content2 instanceof MimeMultipart);
    MimeMultipart textBodyPart = (MimeMultipart) content2;

    return (MimeBodyPart) textBodyPart.getBodyPart(0);
}
 
Example 14
Source File: HttpSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
public static String handleMultipartResponse(String mimeType, InputStream inputStream, IPipeLineSession session, HttpResponseHandler httpHandler) throws IOException, SenderException {
	String result = null;
	try {
		InputStreamDataSource dataSource = new InputStreamDataSource(mimeType, inputStream);
		MimeMultipart mimeMultipart = new MimeMultipart(dataSource);
		for (int i = 0; i < mimeMultipart.getCount(); i++) {
			BodyPart bodyPart = mimeMultipart.getBodyPart(i);
			boolean lastPart = mimeMultipart.getCount() == i + 1;
			if (i == 0) {
				String charset = Misc.DEFAULT_INPUT_STREAM_ENCODING;
				ContentType contentType = ContentType.parse(bodyPart.getContentType());
				if(contentType.getCharset() != null)
					charset = contentType.getCharset().name();

				InputStream bodyPartInputStream = bodyPart.getInputStream();
				result = Misc.streamToString(bodyPartInputStream, charset);
				if (lastPart) {
					bodyPartInputStream.close();
				}
			} else {
				// When the last stream is read the
				// httpMethod.releaseConnection() can be called, hence pass
				// httpMethod to ReleaseConnectionAfterReadInputStream.
				session.put("multipart" + i, new ReleaseConnectionAfterReadInputStream( lastPart ? httpHandler : null, bodyPart.getInputStream()));
			}
		}
	} catch(MessagingException e) {
		throw new SenderException("Could not read mime multipart response", e);
	}
	return result;
}
 
Example 15
Source File: AccessStructure.java    From jplag with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Saves the zip file inside the entries directory
 */
public void saveZipFile(MimeMultipart inputZipFile) {
    try {
        MimeBodyPart bdp = (MimeBodyPart) inputZipFile.getBodyPart(0);
        DataHandler dh = bdp.getDataHandler();
        File part = new File(getEntryPath());
        FileOutputStream fos = new FileOutputStream(part);
        dh.writeTo(fos);
        fos.close();
        System.gc();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
Source File: TestPutEmail.java    From nifi with Apache License 2.0 4 votes vote down vote up
@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, "[email protected]");
    runner.setProperty(PutEmail.MESSAGE, "Message Body");
    runner.setProperty(PutEmail.ATTACH_FILE, "true");
    runner.setProperty(PutEmail.CONTENT_TYPE, "text/html");
    runner.setProperty(PutEmail.TO, "[email protected]");

    Map<String, String> attributes = new HashMap<>();
    attributes.put(CoreAttributes.FILENAME.key(), "test한的ほу́.pdf");
    runner.enqueue("Some text".getBytes(), attributes);

    runner.run();

    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("[email protected]", message.getFrom()[0].toString());
    assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
    assertEquals("[email protected]", 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("test한的ほу́.pdf", MimeUtility.decodeText(attachPart.getFileName()));
    assertEquals("Some text", text);

    assertNull(message.getRecipients(RecipientType.BCC));
    assertNull(message.getRecipients(RecipientType.CC));
}
 
Example 17
Source File: ParseBlobUploadFilter.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
  HttpServletRequest req = (HttpServletRequest) request;
  if (req.getHeader(UPLOAD_HEADER) != null) {
    Map<String, List<String>> blobKeys = new HashMap<String, List<String>>();
    Map<String, List<Map<String, String>>> blobInfos =
        new HashMap<String, List<Map<String, String>>>();
    Map<String, List<String>> otherParams = new HashMap<String, List<String>>();

    try {
      MimeMultipart multipart = MultipartMimeUtils.parseMultipartRequest(req);

      int parts = multipart.getCount();
      for (int i = 0; i < parts; i++) {
        BodyPart part = multipart.getBodyPart(i);
        String fieldName = MultipartMimeUtils.getFieldName(part);
        if (part.getFileName() != null) {
          ContentType contentType = new ContentType(part.getContentType());
          if ("message/external-body".equals(contentType.getBaseType())) {
            String blobKeyString = contentType.getParameter("blob-key");
            List<String> keys = blobKeys.get(fieldName);
            if (keys == null) {
              keys = new ArrayList<String>();
              blobKeys.put(fieldName, keys);
            }
            keys.add(blobKeyString);
            List<Map<String, String>> infos = blobInfos.get(fieldName);
            if (infos == null) {
              infos = new ArrayList<Map<String, String>>();
              blobInfos.put(fieldName, infos);
            }
            infos.add(getInfoFromBody(MultipartMimeUtils.getTextContent(part), blobKeyString));
          }
        } else {
          List<String> values = otherParams.get(fieldName);
          if (values == null) {
            values = new ArrayList<String>();
            otherParams.put(fieldName, values);
          }
          values.add(MultipartMimeUtils.getTextContent(part));
        }
      }
      req.setAttribute(UPLOADED_BLOBKEY_ATTR, blobKeys);
      req.setAttribute(UPLOADED_BLOBINFO_ATTR, blobInfos);
    } catch (MessagingException ex) {
      logger.log(Level.WARNING, "Could not parse multipart message:", ex);
    }

    chain.doFilter(new ParameterServletWrapper(request, otherParams), response);
  } else {
    chain.doFilter(request, response);
  }
}
 
Example 18
Source File: AddFooter.java    From james-project with Apache License 2.0 4 votes vote down vote up
private boolean attachFooterToFirstPart(MimeMultipart multipart) throws MessagingException, IOException {
    MimeBodyPart firstPart = (MimeBodyPart) multipart.getBodyPart(0);
    return attachFooter(firstPart);
}
 
Example 19
Source File: TestPutEmail.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@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, "[email protected]");
    runner.setProperty(PutEmail.MESSAGE, "Message Body");
    runner.setProperty(PutEmail.ATTACH_FILE, "true");
    runner.setProperty(PutEmail.CONTENT_TYPE, "text/html");
    runner.setProperty(PutEmail.TO, "[email protected]");

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

    runner.run();

    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("[email protected]", message.getFrom()[0].toString());
    assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
    assertEquals("[email protected]", 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));
}
 
Example 20
Source File: EmailerTest.java    From cuba with Apache License 2.0 4 votes vote down vote up
private MimeBodyPart getFirstAttachment(MimeMessage msg) throws IOException, MessagingException {
    assertTrue(msg.getContent() instanceof MimeMultipart);
    MimeMultipart mimeMultipart = (MimeMultipart) msg.getContent();
    return (MimeBodyPart) mimeMultipart.getBodyPart(1);
}