Java Code Examples for javax.mail.Message#getContent()

The following examples show how to use javax.mail.Message#getContent() . 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: FlowedMessageUtils.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * Encodes the message content (if text/plain).
 */
public static void flowMessage(Message m, boolean delSp, int width) throws MessagingException, IOException {
    ContentType ct = new ContentType(m.getContentType());
    if (!ct.getBaseType().equals("text/plain")) {
        return;
    }
    String format = ct.getParameter("format");
    String text = format != null && format.equals("flowed") ? deflow(m) : (String) m.getContent();
    String coded = flow(text, delSp, width);
    ct.setParameter("format", "flowed");
    if (delSp) {
        ct.setParameter("delsp", "yes");
    }
    m.setContent(coded, ct.toString());
    m.saveChanges();
}
 
Example 2
Source File: ArdulinkMailMessageCountListener.java    From Ardulink-1 with Apache License 2.0 6 votes vote down vote up
private String getContent(Message message) throws IOException, MessagingException {

		String retvalue = "";
		
		Object msgContent = message.getContent();
		if(msgContent instanceof Multipart) {
			Multipart multipart = (Multipart)message.getContent();
			int count = multipart.getCount();
			for(int i = 0; i < count; i++) {
				BodyPart part = multipart.getBodyPart(i);
				if(part.isMimeType("text/plain")) {
					retvalue += "Part" + i + ": " + part.getContent().toString();
				}
			}
		} else {
			retvalue = msgContent.toString();
		}
		
		return retvalue;
	}
 
Example 3
Source File: EmailReader.java    From baleen with Apache License 2.0 6 votes vote down vote up
private List<String> getAttachments(Message msg) throws MessagingException, IOException {
  Object messageContentObject = msg.getContent();

  List<String> attachments = new ArrayList<>();

  if (messageContentObject instanceof Multipart) {
    Multipart multipart = (Multipart) msg.getContent();

    for (int i = 0; i < multipart.getCount(); i++) {
      Part part = multipart.getBodyPart(i);

      if (!Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())
          && StringUtils.isBlank(part.getFileName())) {
        continue;
      }

      attachments.add(part.getFileName());
    }
  }

  return attachments;
}
 
Example 4
Source File: MailReader.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Get the content of a mail message.
 * 
 * @param message
 *            the mail message
 * @return the content of the mail message
 */
private String getMessageContent(Message message) throws MessagingException {
    try {
        Object content = message.getContent();
        if (content instanceof Multipart) {
            StringBuffer messageContent = new StringBuffer();
            Multipart multipart = (Multipart) content;
            for (int i = 0; i < multipart.getCount(); i++) {
                Part part = multipart.getBodyPart(i);
                if (part.isMimeType("text/plain")) {
                    messageContent.append(part.getContent().toString());
                }
            }
            return messageContent.toString();
        }
        return content.toString();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 5
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 6
Source File: LargeMessageTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve message from retriever and check the body content
 *
 * @param server Server to read from
 * @param to     Account to retrieve
 */
private void retrieveAndCheckBody(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().equalsIgnoreCase("application/blubb"));

        // Check content
        InputStream contentStream = (InputStream) message.getContent();
        byte[] bytes = IOUtils.toByteArray(contentStream);
        assertArrayEquals(createLargeByteArray(), bytes);

        // Dump complete mail message. This leads to a FETCH command without section or "len" specified.
        message.writeTo(new ByteArrayOutputStream());
    }
}
 
Example 7
Source File: Mail.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
protected static void processMessageContent(Message message, Mail mail) throws MessagingException, IOException {

    if (isMultipartMessage(message)) {
      Multipart multipart = (Multipart) message.getContent();

      int numberOfParts = multipart.getCount();
      for (int partCount = 0; partCount < numberOfParts; partCount++) {
        BodyPart bodyPart = multipart.getBodyPart(partCount);

        processMessagePartContent(bodyPart, mail);
      }

    } else {
      processMessagePartContent(message, mail);
    }
  }
 
Example 8
Source File: MailManager.java    From vpn-over-dns with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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.}
		// préférer 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 {
			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 "";
	}
}
 
Example 9
Source File: EmailDataFactory.java    From bobcat with Apache License 2.0 5 votes vote down vote up
private String getMessageContent(Message message) throws IOException, MessagingException {
  String contentString = null;
  Object content = message.getContent();
  if (content instanceof Multipart) {
    StringBuilder contentBuilder = processMultipart((Multipart) content);
    contentString = contentBuilder.toString();
  } else if (message.getContentType().toLowerCase().contains("text")) {
    contentString = message.getContent().toString();
  }
  return contentString;
}
 
Example 10
Source File: ReadEmailImap.java    From opentest with MIT License 5 votes vote down vote up
/**
 * Extracts the text content of an email message with support for multipart
 * messages
 */
private String getTextFromMessage(Message message) throws Exception {
    String result = "";
    if (message.isMimeType("multipart/*")) {
        MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
        result = getTextFromMimeMultipart(mimeMultipart);
    } else {
        Object content = message.getContent();
        result = content.toString();
    }

    return result;
}
 
Example 11
Source File: EmailSteps.java    From datamill with ISC License 5 votes vote down vote up
private String getCompleteContent(Message message) throws IOException, MessagingException {
    StringBuilder completeContent = new StringBuilder();

    MimeMultipart contents = (MimeMultipart) message.getContent();
    for (int i = 0; i < contents.getCount(); i++) {
        BodyPart part = contents.getBodyPart(i);
        String partText = getPartTextContent(part);

        completeContent.append(partText);
    }

    return completeContent.toString();
}
 
Example 12
Source File: EmailReader.java    From baleen with Apache License 2.0 5 votes vote down vote up
private Boolean hasAttachments(Message msg) throws MessagingException, IOException {
  if (msg.isMimeType("multipart/mixed")) {
    Multipart mp = (Multipart) msg.getContent();
    if (mp.getCount() > 1) {
      return true;
    }
  }

  return false;
}
 
Example 13
Source File: AssertEmail.java    From ogham with Apache License 2.0 5 votes vote down vote up
private static void assertEquals(ExpectedMultiPartEmail expectedEmail, Message actualEmail, boolean strict, AssertionRegistry assertions) throws MessagingException, IOException {
	assertHeaders(expectedEmail, actualEmail, assertions);
	Object content = actualEmail == null ? null : actualEmail.getContent();
	assertions.register(() -> Assert.assertTrue("should be multipart message", content instanceof Multipart));
	List<Part> bodyParts = actualEmail == null ? emptyList() : getBodyParts(actualEmail);
	assertions.register(() -> Assert.assertEquals("should have " + expectedEmail.getExpectedContents().size() + " parts", expectedEmail.getExpectedContents().size(), bodyParts.size()));
	for (int i = 0; i < expectedEmail.getExpectedContents().size(); i++) {
		Part part = i < bodyParts.size() ? bodyParts.get(i) : null;
		assertBody("body[" + i + "]", expectedEmail.getExpectedContents().get(i).getBody(), part == null || part.getContent() == null ? null : part.getContent().toString(), strict, assertions);
		assertMimetype(expectedEmail.getExpectedContents().get(i), part == null ? null : part.getContentType(), assertions);
	}
}
 
Example 14
Source File: FlowedMessageUtils.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Obtains the content of the encoded message, if previously encoded as <code>format=flowed</code>.
 */
public static String deflow(Message m) throws IOException, MessagingException {
    ContentType ct = new ContentType(m.getContentType());
    String format = ct.getParameter("format");
    if (ct.getBaseType().equals("text/plain") && format != null && format.equalsIgnoreCase("flowed")) {
        String delSp = ct.getParameter("delsp");
        return deflow((String) m.getContent(), delSp != null && delSp.equalsIgnoreCase("yes"));
        
    } else if (ct.getPrimaryType().equals("text")) {
        return (String) m.getContent();
    } else {
        return null;
    }
}
 
Example 15
Source File: ArdulinkMailMessageCountListener.java    From Ardulink-1 with Apache License 2.0 5 votes vote down vote up
private boolean isMultipartValid(Message message) throws MessagingException, IOException {
	boolean retvalue = false;
	Multipart multipart = (Multipart)message.getContent();
	int count = multipart.getCount();
	for(int i = 0; i < count; i++) {
		BodyPart part = multipart.getBodyPart(i);
		if(part.isMimeType("text/plain")) {
			retvalue = true;
		}
	}
	
	return retvalue;
}
 
Example 16
Source File: MailSteps.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @param message
 * @return
 * @throws MessagingException
 * @throws IOException
 */
private static String getTextFromMessage(Message message) throws MessagingException, IOException {
    String result = "";
    if (message.isMimeType("text/plain")) {
        result = message.getContent().toString();
    } else if (message.isMimeType("multipart/*")) {
        final MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
        result = getTextFromMimeMultipart(mimeMultipart);
    }
    return result;
}
 
Example 17
Source File: Mail.java    From camunda-bpm-mail with Apache License 2.0 4 votes vote down vote up
protected static boolean isMultipartMessage(Message message) throws MessagingException, IOException {
  return message.isMimeType("multipart")
      || message.getContent() instanceof Multipart;
}
 
Example 18
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 19
Source File: TableLoaderInbox.java    From hana-native-adapters with Apache License 2.0 4 votes vote down vote up
@Override
protected void setColumnValue(int tablecolumnindex, int returncolumnindex, AdapterRow row, Object o) throws AdapterException {
	Message msg = (Message) o;
	try {
    	switch (tablecolumnindex) {
    	case 0:
    		Address from;
    		if (msg.getFrom().length > 0) {
    			from = msg.getFrom()[0];
	    		row.setColumnValue(returncolumnindex, checkLength(from.toString(), 127));
    		} else {
	    		row.setColumnNull(returncolumnindex);
    		}
    		break;
    	case 1:
    		row.setColumnValue(returncolumnindex, checkLength(msg.getSubject(), 512));
    		break;
    	case 2:
    		row.setColumnValue(returncolumnindex, new Timestamp(msg.getReceivedDate()));
    		break;
    	case 3:
    		row.setColumnValue(returncolumnindex, new Timestamp(msg.getSentDate()));
    		break;
    	case 4:
    		row.setColumnValue(returncolumnindex, checkLength(msg.getContentType(), 127));
    		break;
    	case 5:
    		row.setColumnValue(returncolumnindex, msg.getSize());
    		break;
    	case 6:
    		Address reply;
    		if (msg.getReplyTo() != null && msg.getReplyTo().length > 0) {
    			reply = msg.getReplyTo()[0];
    			row.setColumnValue(returncolumnindex, checkLength(reply.toString(), 1024));
    		} else {
    			row.setColumnNull(returncolumnindex);
    		}
    		break;
    	case 7:
    		Object contentObj = msg.getContent();
    		String resultString = null;
    		if (contentObj instanceof Multipart) {
    			BodyPart clearTextPart = null;
    			BodyPart htmlTextPart = null;
    			Multipart content = (Multipart)contentObj;
    			int count = content.getCount();
    			for(int i=0; i<count; i++)
    			{
    				BodyPart part =  content.getBodyPart(i);
    				if (part.isMimeType("text/plain")) {
    					clearTextPart = part;
    					break;
    				}
    				else if(part.isMimeType("text/html")) {
    					htmlTextPart = part;
    				}
    			}

    			if (clearTextPart != null) {
    				resultString = (String) clearTextPart.getContent();
    			} else if (htmlTextPart != null) {
    				String html = (String) htmlTextPart.getContent();
    				resultString = Jsoup.parse(html).text();
    			}

    		} else if (contentObj instanceof String) {
    			if (msg.getContentType().startsWith("text/html")) {
    				resultString = Jsoup.parse((String) contentObj).text();
    			} else {
    				resultString = (String) contentObj;
    			}
    		} else {
    			resultString = contentObj.toString();
    		}
    		row.setColumnValue(returncolumnindex, checkLength(resultString, 5000));
    		break;
    	}		
	} catch (MessagingException | IOException e) {
		throw new AdapterException(e);
	}
}
 
Example 20
Source File: EmailUtils.java    From testgrid with Apache License 2.0 4 votes vote down vote up
public void openEmail(Message message) throws Exception {
    message.getContent();
}