javax.mail.BodyPart#getContent ( )源码实例Demo

下面列出了javax.mail.BodyPart#getContent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: document-management-software   文件: MailUtil.java
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);
	}
}
 
源代码2 项目: quarkus   文件: MailerImplTest.java
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;
}
 
源代码3 项目: quarkus   文件: MailerImplTest.java
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();
}
 
源代码4 项目: NoraUi   文件: MailSteps.java
/**
 * @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();
}
 
源代码5 项目: ats-framework   文件: MimePackage.java
/**
 * 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;
}
 
源代码6 项目: opentest   文件: ReadEmailImap.java
/**
 * 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);
}
 
源代码7 项目: scava   文件: NntpUtil.java
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 "";
}
 
源代码8 项目: job   文件: Job51ResumeParser.java
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;
}
 
源代码9 项目: codenvy   文件: MailReceiverUtils.java
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();
}
 
源代码10 项目: teammates   文件: EmailAccount.java
/**
 * 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;
}
 
源代码11 项目: greenmail   文件: LargeMessageTest.java
/**
 * 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);
    }
}
 
源代码12 项目: quarkus   文件: MailerImplTest.java
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;
}
 
源代码13 项目: syndesis   文件: EMailReceiveCustomizer.java
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();
}
 
源代码14 项目: commons-email   文件: MultiPartEmail.java
/**
 * 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);
    }
}
 
源代码15 项目: scipio-erp   文件: MimeMessageWrapper.java
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;
    }
}
 
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;
}
 
源代码17 项目: vpn-over-dns   文件: MailManager.java
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();
}
 
源代码18 项目: james-project   文件: DSNBounceTest.java
@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");
}
 
源代码19 项目: hana-native-adapters   文件: TableLoaderInbox.java
@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);
	}
}
 
源代码20 项目: james-project   文件: ClassifyBounce.java
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;
        }