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

The following examples show how to use javax.mail.BodyPart#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: MailUtil.java    From document-management-software with GNU Lesser General Public License v3.0 7 votes vote down vote up
private static void addAttachments(BodyPart p, EMail email, boolean extractAttachmentContent)
		throws UnsupportedEncodingException, MessagingException, IOException {
	if (p.isMimeType("multipart/*")) {
		Multipart mp = (Multipart) p.getContent();
		int count = mp.getCount();
		for (int i = 1; i < count; i++) {
			BodyPart bp = mp.getBodyPart(i);
			if (bp.getFileName() != null && extractAttachmentContent) {
				addAttachment(bp, email);
			} else if (bp.isMimeType("multipart/*")) {
				addAttachments(bp, email, extractAttachmentContent);
			}
		}
	} else if (extractAttachmentContent && StringUtils.isNotEmpty(p.getFileName())) {
		addAttachment(p, email);
	}
}
 
Example 2
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 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: EmailAccount.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the text from multipart/alternative, the type of text returned follows the preference of the sending agent.
 */
private String getTextFromMultiPartAlternative(Multipart multipart) throws IOException, MessagingException {
    // search in reverse order as a multipart/alternative should have their most preferred format last
    for (int i = multipart.getCount() - 1; i >= 0; i--) {
        BodyPart bodyPart = multipart.getBodyPart(i);

        if (bodyPart.isMimeType("text/html")) {
            return (String) bodyPart.getContent();
        } else if (bodyPart.isMimeType("text/plain")) {
            // Since we are looking in reverse order, if we did not encounter a text/html first we can return the plain
            // text because that is the best preferred format that we understand. If a text/html comes along later it
            // means the agent sending the email did not set the html text as preferable or did not set their preferred
            // order correctly, and in that case we do not handle that.
            return (String) bodyPart.getContent();
        } else if (bodyPart.isMimeType("multipart/*") || bodyPart.isMimeType("message/rfc822")) {
            String text = getTextFromPart(bodyPart);
            if (text != null) {
                return text;
            }
        }
    }
    // we do not know how to handle the text in the multipart or there is no text
    return null;
}
 
Example 5
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 6
Source File: Job51ResumeParser.java    From job with MIT License 6 votes vote down vote up
private String parseHtml(BodyPart body) throws Exception {
  //System.err.println(body.getContentType());
  if(body.getContentType().startsWith("text/html")) {
    Object content = body.getContent();
    return content == null ? null : content.toString();
  } else if(body.getContentType().startsWith("multipart")) {
    Multipart subpart = (Multipart) body.getContent();
    for(int j = 0; j < subpart.getCount(); j++) {
      BodyPart subbody = subpart.getBodyPart(j);
      String html = parseHtml(subbody);
      if(html != null) {
        return html;
      }
    }
  }
  return null;
}
 
Example 7
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 8
Source File: ReadEmailImap.java    From opentest with MIT License 6 votes vote down vote up
/**
 * Extracts the text content from a multipart email message.
 */
private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws Exception {
    ArrayList<String> partStrings = new ArrayList<>();
    
    int partCount = mimeMultipart.getCount();
    for (int i = 0; i < partCount; i++) {
        BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.isMimeType("text/plain")) {
            partStrings.add((String)bodyPart.getContent());
        } else if (bodyPart.isMimeType("text/html")) {
            partStrings.add((String)bodyPart.getContent());
        } else if (bodyPart.getContent() instanceof MimeMultipart) {
            partStrings.add(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
        }
    }
    
    return String.join("\n", partStrings);
}
 
Example 9
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Check if the body is from the content type and returns it if not attachment
 *
 * @param mimePart
 * @param contentType
 * @return null if not with specific content type or part is attachment
 */
private String getBodyIfNotAttachment(
                                       BodyPart mimePart,
                                       String contentType ) throws MessagingException, IOException {

    String mimePartContentType = mimePart.getContentType().toLowerCase();
    if (mimePartContentType.startsWith(contentType)) { // found a part with given mime type
        String contentDisposition = mimePart.getDisposition();
        if (!Part.ATTACHMENT.equalsIgnoreCase(contentDisposition)) {
            Object partContent = mimePart.getContent();
            if (partContent instanceof InputStream) {
                return IoUtils.streamToString((InputStream) partContent);
            } else {
                return partContent.toString();
            }
        }
    }
    return null;
}
 
Example 10
Source File: MailSteps.java    From NoraUi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @param mimeMultipart
 * @return
 * @throws MessagingException
 * @throws IOException
 */
private static String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException {
    final StringBuilder result = new StringBuilder();
    final int count = mimeMultipart.getCount();
    for (int i = 0; i < count; i++) {
        final BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.isMimeType("text/plain")) {
            result.append("\n");
            result.append(bodyPart.getContent());
        } else if (bodyPart.isMimeType("text/html")) {
            result.append("\n");
            result.append((String) bodyPart.getContent());
        } else if (bodyPart.getContent() instanceof MimeMultipart) {
            result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
        }
    }
    return result.toString();
}
 
Example 11
Source File: MailerImplTest.java    From quarkus with Apache License 2.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_CONTENT_TYPE)) {
            result.append("\n").append(bodyPart.getContent());
            break; // without break same text appears twice in my tests
        } else if (bodyPart.isMimeType("text/html")) {
            result.append("\n").append(bodyPart.getContent());
        } else if (bodyPart.getContent() instanceof MimeMultipart) {
            result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
        }
    }
    return result.toString();
}
 
Example 12
Source File: MultiPartEmail.java    From commons-email with Apache License 2.0 5 votes vote down vote up
/**
 * Does the work of actually building the MimeMessage. Please note that
 * a user rarely calls this method directly and only if he/she is
 * interested in the sending the underlying MimeMessage without
 * commons-email.
 *
 * @throws EmailException if there was an error.
 * @since 1.0
 */
@Override
public void buildMimeMessage() throws EmailException
{
    try
    {
        if (primaryBodyPart != null)
        {
            // before a multipart message can be sent, we must make sure that
            // the content for the main body part was actually set.  If not,
            // an IOException will be thrown during super.send().

            final BodyPart body = this.getPrimaryBodyPart();
            try
            {
                body.getContent();
            }
            catch (final IOException e) // NOPMD
            {
                // do nothing here.
                // content will be set to an empty string as a result.
                // (Should this really be rethrown as an email exception?)
                // throw new EmailException(e);
            }
        }

        if (subType != null)
        {
            getContainer().setSubType(subType);
        }

        super.buildMimeMessage();
    }
    catch (final MessagingException me)
    {
        throw new EmailException(me);
    }
}
 
Example 13
Source File: EMailReceiveCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static String getPlainTextFromMultipart(Multipart multipart)  throws MessagingException, IOException {
    StringBuilder result = new StringBuilder();
    int count = multipart.getCount();
    for (int i = 0; i < count; i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        if (bodyPart.isMimeType(TEXT_PLAIN)) {
            result.append(NEW_LINE)
                        .append(bodyPart.getContent());
            break; // without break same text can appear twice
        } else if (bodyPart.isMimeType(TEXT_HTML)) {
            result.append(NEW_LINE)
                        .append(Jsoup.parse((String) bodyPart.getContent()).text());
            break; // without break same text can appear twice
        } else if (bodyPart.isMimeType("application/pgp-encrypted")) {
            //
            // Body is encrypted so flag as such to enable easy understanding for users
            //
            result.append(NEW_LINE)
                        .append("<pgp encrypted text>")
                        .append(NEW_LINE)
                        .append(bodyPart.getContent().toString());
        } else if (bodyPart.getContent() instanceof MimeMultipart){
            result.append(NEW_LINE)
                        .append(getPlainTextFromMultipart((MimeMultipart) bodyPart.getContent()));
        }
    }
    return result.toString();
}
 
Example 14
Source File: MimeMessageWrapper.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public int getSubPartCount(int index) {
    BodyPart part = getPart(Integer.toString(index));
    try {
        Object content = part.getContent();
        if (content instanceof Multipart) {
            return ((Multipart) content).getCount();
        }
        return 0;
    } catch (Exception e) {
        Debug.logError(e, module);
        return -1;
    }
}
 
Example 15
Source File: DefaultReceiveEmailProvider.java    From xframium-java with GNU General Public License v3.0 5 votes vote down vote up
private String getTextFromBodyPart( BodyPart bodyPart ) throws IOException, MessagingException
{

    String result = "";
    if ( bodyPart.getContentType().startsWith( "text/" ) )
    {
        result = (String) bodyPart.getContent();
    }
    else if ( bodyPart.getContent() instanceof MimeMultipart )
    {
        result = getTextFromMimeMultipart( (MimeMultipart) bodyPart.getContent() );
    }

    return result;
}
 
Example 16
Source File: MailManager.java    From vpn-over-dns with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String getMultipartContentString(final MimeMultipart multipart, final boolean mixed) throws IOException, MessagingException {
	// content-type: multipart/mixed ou multipart/alternative

	final StringBuffer selected_content = new StringBuffer();
	for (int i = 0; i < multipart.getCount(); i++) {
		final BodyPart body_part = multipart.getBodyPart(i);
		final Object content = body_part.getContent();

		final String content_string;
		if (String.class.isInstance(content))
			if (body_part.isMimeType("text/html")) content_string = GenericTools.html2Text((String) content);
			else if (body_part.isMimeType("text/plain")) content_string = (String) content;
			else {
				log.warn("body part content-type not handled: " + body_part.getContentType() + " -> downgrading to String");
				content_string = (String) content;
			}
		else if (MimeMultipart.class.isInstance(content)) {
			boolean part_mixed = false;
			if (body_part.isMimeType("multipart/mixed")) part_mixed = true;
			else if (body_part.isMimeType("multipart/alternative")) part_mixed = false;
			else {
				log.warn("body part content-type not handled: " + body_part.getContentType() + " -> downgrading to multipart/mixed");
				part_mixed = true;
			}
			content_string = getMultipartContentString((MimeMultipart) content, part_mixed);
		} else {
			log.warn("invalid body part content type and class: " + content.getClass().toString() + " - " + body_part.getContentType());
			content_string = "";
		}

		if (mixed == false) {
			// on sélectionne la première part non vide - ce n'est pas forcément la meilleure alternative, mais comment différentiel un text/plain d'une pièce jointe d'un text/plain du corps du message, accompagnant un text/html du même corps ???
			if (selected_content.length() == 0) selected_content.append(content_string);
		} else {
			if (selected_content.length() > 0 && content_string.length() > 0) selected_content.append("\r\n---\r\n");
			selected_content.append(content_string);
		}
	}
	return selected_content.toString();
}
 
Example 17
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 18
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 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: ClassifyBounce.java    From james-project with Apache License 2.0 4 votes vote down vote up
private String getRawText(Object o) throws MessagingException, IOException {

            String s = null;

            if (o instanceof Multipart) {
                Multipart multi = (Multipart) o;
                for (int i = 0; i < multi.getCount(); i++) {
                    s = getRawText(multi.getBodyPart(i));
                    if (s != null) {
                        if (s.length() > 0) {
                            break;
                        }
                    }
                }
            } else if (o instanceof BodyPart) {
                BodyPart aBodyContent = (BodyPart) o;
                StringTokenizer aTypeTokenizer = new StringTokenizer(aBodyContent.getContentType(), "/");
                String abstractType = aTypeTokenizer.nextToken();
                if (abstractType.compareToIgnoreCase("MESSAGE") == 0) {
                    Message inlineMessage = (Message) aBodyContent.getContent();
                    s = getRawText(inlineMessage.getContent());
                }
                if (abstractType.compareToIgnoreCase("APPLICATION") == 0) {
                    s = "Attached File: " + aBodyContent.getFileName();
                }
                if (abstractType.compareToIgnoreCase("TEXT") == 0) {
                    try {
                        Object oS = aBodyContent.getContent();
                        if (oS instanceof String) {
                            s = (String) oS;
                        } else {
                            throw (new MessagingException("Unkown MIME Type (?): " + oS.getClass()));
                        }
                    } catch (Exception e) {
                        throw (new MessagingException("Unable to read message contents (" + e.getMessage() + ")"));
                    }
                }
                if (abstractType.compareToIgnoreCase("MULTIPART") == 0) {
                    s = getRawText(aBodyContent.getContent());
                }
            }

            if (o instanceof String) {
                s = (String) o;
            }

            return s;
        }