javax.mail.Multipart#getBodyPart ( )源码实例Demo

下面列出了javax.mail.Multipart#getBodyPart ( ) 实例代码,或者点击链接到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 项目: alfresco-repository   文件: EMLTransformer.java
/**
 * Find "text" parts of message recursively and appends it to sb StringBuilder
 * 
 * @param multipart Multipart to process
 * @param sb StringBuilder 
 * @throws MessagingException
 * @throws IOException
 */
private void processMultiPart(Multipart multipart, StringBuilder sb) throws MessagingException, IOException
{
    boolean isAlternativeMultipart = multipart.getContentType().contains(MimetypeMap.MIMETYPE_MULTIPART_ALTERNATIVE);
    if (isAlternativeMultipart)
    {
        processAlternativeMultipart(multipart, sb);
    }
    else
    {
        for (int i = 0, n = multipart.getCount(); i < n; i++)
        {
            Part part = multipart.getBodyPart(i);
            if (part.getContent() instanceof Multipart)
            {
                processMultiPart((Multipart) part.getContent(), sb);
            }
            else
            {
                processPart(part, sb);
            }
        }
    }
}
 
源代码3 项目: camunda-bpm-mail   文件: Mail.java
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);
    }
  }
 
源代码4 项目: scada   文件: MailUtils.java
/**
 * ����ʼ��ı�����
 * @param part �ʼ���
 * @param content �洢�ʼ��ı����ݵ��ַ���
 */ 
public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException { 
    //������ı����͵ĸ�����ͨ��getContent��������ȡ���ı����ݣ����ⲻ��������Ҫ�Ľ��������������Ҫ���ж� 
    boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;  
    if (part.isMimeType("text/*") && !isContainTextAttach) { 
        content.append(part.getContent().toString()); 
    } else if (part.isMimeType("message/rfc822")) {  
        getMailTextContent((Part)part.getContent(),content); 
    } else if (part.isMimeType("multipart/*")) { 
        Multipart multipart = (Multipart) part.getContent(); 
        int partCount = multipart.getCount(); 
        for (int i = 0; i < partCount; i++) { 
            BodyPart bodyPart = multipart.getBodyPart(i); 
            getMailTextContent(bodyPart,content); 
        } 
    } 
}
 
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;
	}
 
源代码6 项目: development   文件: MailReader.java
/**
 * 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 "";
}
 
源代码7 项目: baleen   文件: EmailReader.java
private String getContent(Message msg) throws IOException, MessagingException {
  Object messageContentObject = msg.getContent();
  if (messageContentObject instanceof Multipart) {
    Multipart multipart = (Multipart) msg.getContent();

    // Loop over the parts of the email
    for (int i = 0; i < multipart.getCount(); i++) {
      // Retrieve the next part
      Part part = multipart.getBodyPart(i);

      if (!Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())
          && StringUtils.isBlank(part.getFileName())) {
        return part.getContent().toString();
      }
    }
  } else {
    return msg.getContent().toString().trim();
  }

  return "";
}
 
@Test
public void contentDispositionOfAttachmentShouldBeOverwrittenWhenOriginalMessageHasContentDisposition() throws Exception {
    String messageContent = "Content-type: text/calendar; method=REPLY; charset=UTF-8\n" +
        "Content-Disposition: inline\n" +
        "\n" +
        "BEGIN:VCALENDAR\n" +
        "END:VEVENT\n" +
        "END:VCALENDAR";
    MimeMessage message = MimeMessageUtil.mimeMessageFromString(messageContent);

    Mail mail = FakeMail.builder()
        .name("name")
        .mimeMessage(message)
        .build();

    mailet.service(mail);

    Multipart multipart = (Multipart)mail.getMessage().getContent();

    int firstBodyPartIndex = 0;
    BodyPart firstBodyPart = multipart.getBodyPart(firstBodyPartIndex);
    assertThat(firstBodyPart.getHeader("Content-Disposition")).containsExactly("attachment");
}
 
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;
	}
 
源代码10 项目: FairEmail   文件: MessageHelper.java
static void overrideContentTransferEncoding(Multipart mp) throws MessagingException, IOException {
    for (int i = 0; i < mp.getCount(); i++) {
        Part part = mp.getBodyPart(i);
        Object content = part.getContent();
        if (content instanceof Multipart) {
            part.setHeader("Content-Transfer-Encoding", "7bit");
            overrideContentTransferEncoding((Multipart) content);
        } else
            part.setHeader("Content-Transfer-Encoding", "base64");
    }
}
 
源代码11 项目: 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();
}
 
源代码12 项目: bobcat   文件: EmailDataFactory.java
private StringBuilder processMultipart(final Multipart multipart)
    throws MessagingException,
    IOException {
  StringBuilder messageContent = new StringBuilder();
  Part part;
  for (int i = 0; i < multipart.getCount(); i++) {
    part = multipart.getBodyPart(i);
    if (part.getContent() instanceof Multipart) {
      messageContent.append(processMultipart((Multipart) part.getContent()));
    } else if (isPartTextLike(part)) {
      messageContent.append(part.getContent()).append('\n');
    }
  }
  return messageContent;
}
 
源代码13 项目: scada   文件: MailUtils.java
/** 
 * ���渽�� 
 * @param part �ʼ��ж��������е�����һ������� 
 * @param destDir  ��������Ŀ¼ 
 */ 
public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException, 
        FileNotFoundException, IOException { 
    if (part.isMimeType("multipart/*")) { 
        Multipart multipart = (Multipart) part.getContent();    //�������ʼ� 
        //�������ʼ���������ʼ��� 
        int partCount = multipart.getCount(); 
        for (int i = 0; i < partCount; i++) { 
            //��ø������ʼ�������һ���ʼ��� 
            BodyPart bodyPart = multipart.getBodyPart(i); 
            //ijһ���ʼ���Ҳ�п������ɶ���ʼ�����ɵĸ����� 
            String disp = bodyPart.getDisposition(); 
            if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { 
                InputStream is = bodyPart.getInputStream(); 
                saveFile(is, destDir, decodeText(bodyPart.getFileName())); 
            } else if (bodyPart.isMimeType("multipart/*")) { 
                saveAttachment(bodyPart,destDir); 
            } else { 
                String contentType = bodyPart.getContentType(); 
                if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) { 
                    saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName())); 
                } 
            } 
        } 
    } else if (part.isMimeType("message/rfc822")) { 
        saveAttachment((Part) part.getContent(),destDir); 
    } 
}
 
源代码14 项目: job   文件: ZhilianEmailResumeParser.java
protected Document parse2Html(File file) throws Exception {
  InputStream in = new FileInputStream(file);

  Session mailSession = Session.getDefaultInstance(System.getProperties(), null);

  MimeMessage msg = new MimeMessage(mailSession, in);

  Multipart part = (Multipart) msg.getContent();
  String html = "";
  for(int i = 0; i < part.getCount(); i++) {
    BodyPart body = part.getBodyPart(i);
    String type = body.getContentType();
    if(type.startsWith("text/html")) {
      html = body.getContent().toString();
      break;
    }
  }
  in.close();
  
  if(html == null || html.length() == 0) {
    String content = FileUtils.readFileToString(file);
    final String endFlag = "</html>";
    int start = content.indexOf("<html");
    int end = content.indexOf(endFlag);
    content = content.substring(start, end + endFlag.length());
    html = QuotedPrintableUtils.decode(content.getBytes(), "gb2312");
    System.err.println(html);
  }
  return Jsoup.parse(html);
}
 
@Test
public void contentTransferEncodingOfAttachmentShouldBeTakenFromOriginalMessage() throws Exception {
    Mail mail = FakeMail.builder()
        .name("name")
        .mimeMessage(calendarMessage)
        .build();

    mailet.service(mail);

    Multipart multipart = (Multipart)mail.getMessage().getContent();

    int firstBodyPartIndex = 0;
    BodyPart firstBodyPart = multipart.getBodyPart(firstBodyPartIndex);
    assertThat(firstBodyPart.getHeader("Content-transfer-encoding")).containsExactly("8BIT");
}
 
@Test
public void contentTypeOfAttachmentShouldBeTakenFromOriginalMessage() throws Exception {
    Mail mail = FakeMail.builder()
        .name("name")
        .mimeMessage(calendarMessage)
        .build();

    mailet.service(mail);

    Multipart multipart = (Multipart)mail.getMessage().getContent();

    int firstBodyPartIndex = 0;
    BodyPart firstBodyPart = multipart.getBodyPart(firstBodyPartIndex);
    assertThat(firstBodyPart.getContentType()).isEqualTo("text/calendar; method=REPLY; charset=UTF-8");
}
 
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;
}
 
源代码18 项目: anyline   文件: Pop3Util.java
/** 
 * 保存附件 
 *  
 * @param part  邮件中多个组合体中的其中一个组合体 
 * @param dir  附件保存目录 
 * @param sendTime sendTime
 * @param files files
 * @throws UnsupportedEncodingException UnsupportedEncodingException 
 * @throws MessagingException MessagingException 
 * @throws FileNotFoundException FileNotFoundException 
 * @throws IOException  IOException
 * @return List
 */ 

public static List<File> downloadAttachment(Part part, String dir, Date sendTime, List<File> files) throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException { 
	if (BasicUtil.isEmpty(files)) { 
		files = new ArrayList<File>(); 
	} 
	dir = dir.replace("{send_date}", DateUtil.format(sendTime,"yyyyMMdd")); 
	dir = dir.replace("{send_time}", DateUtil.format(sendTime,"yyyyMMddhhmmss")); 
	if (part.isMimeType("multipart/*")) { 
		Multipart multipart = (Multipart) part.getContent(); // 复杂体邮件 
		int partCount = multipart.getCount(); 
		for (int i = 0; i < partCount; i++) { 
			boolean result = false; 
			BodyPart bodyPart = multipart.getBodyPart(i); 
			String disp = bodyPart.getDisposition(); 
			String name = decode(bodyPart.getFileName()); 
			String path = null; 
			if(dir.contains("{file}")){ 
				path = dir.replace("{file}", name); 
			}else{ 
				path = FileUtil.mergePath(dir, name); 
			} 
			File file =  new File(path); 
			if (BasicUtil.isNotEmpty(name) && disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { 
				result = FileUtil.save(bodyPart.getInputStream(), file); 
			} else if (bodyPart.isMimeType("multipart/*")) { 
				downloadAttachment(bodyPart, dir, sendTime, files); 
			} else if(BasicUtil.isNotEmpty(name)){ 
				String contentType = bodyPart.getContentType(); 
				if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) { 
					result = FileUtil.save(bodyPart.getInputStream(), file); 
				} 
			} 
			if (result) { 
				files.add(file); 
			} 
		} 
	} else if (part.isMimeType("message/rfc822")) { 
		downloadAttachment((Part) part.getContent(), dir, sendTime, files); 
	} 
	return files; 
}
 
源代码19 项目: alfresco-repository   文件: AttachmentsExtractor.java
public void extractAttachments(NodeRef messageRef, MimeMessage originalMessage) throws IOException, MessagingException
{
    NodeRef attachmentsFolderRef = null;
    String attachmentsFolderName = null;
    boolean createFolder = false;
    switch (attachmentsExtractorMode)
    {
    case SAME:
        attachmentsFolderRef = nodeService.getPrimaryParent(messageRef).getParentRef();
        break;
    case COMMON:
        attachmentsFolderRef = this.attachmentsFolderRef;
        break;
    case SEPARATE:
    default:
        String messageName = (String) nodeService.getProperty(messageRef, ContentModel.PROP_NAME);
        attachmentsFolderName = messageName + "-attachments";
        createFolder = true;
        break;
    }
    if (!createFolder)
    {
        nodeService.createAssociation(messageRef, attachmentsFolderRef, ImapModel.ASSOC_IMAP_ATTACHMENTS_FOLDER);
    }
 
    Object content = originalMessage.getContent();
    if (content instanceof Multipart)
    {
        Multipart multipart = (Multipart) content;
 
        for (int i = 0, n = multipart.getCount(); i < n; i++)
        {
            Part part = multipart.getBodyPart(i);
            if ("attachment".equalsIgnoreCase(part.getDisposition()))
            {
                if (createFolder)
                {
                    attachmentsFolderRef = createAttachmentFolder(messageRef, attachmentsFolderName);
                    createFolder = false;
                }
                createAttachment(messageRef, attachmentsFolderRef, part);
            }
        }
    }
 
}
 
源代码20 项目: james-project   文件: AttachmentFileNameIs.java
/**
 * Checks if <I>part</I> matches with at least one of the <CODE>masks</CODE>.
 * 
 * @param part
 */
protected boolean matchFound(Part part) throws Exception {
    
    /*
     * if there is an attachment and no inline text,
     * the content type can be anything
     */
    
    if (part.getContentType() == null ||
        part.getContentType().startsWith("multipart/alternative")) {
        return false;
    }
    
    Object content;
    
    try {
        content = part.getContent();
    } catch (UnsupportedEncodingException uee) {
        // in this case it is not an attachment, so ignore it
        return false;
    }
    
    Exception anException = null;
    
    if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;
        for (int i = 0; i < multipart.getCount(); i++) {
            try {
                Part bodyPart = multipart.getBodyPart(i);
                if (matchFound(bodyPart)) {
                    return true; // matching file found
                }
            } catch (MessagingException e) {
                anException = e;
            } // remember any messaging exception and process next bodypart
        }
    } else {
        String fileName = part.getFileName();
        if (fileName != null) {
            fileName = cleanFileName(fileName);
            // check the file name
            if (matchFound(fileName)) {
                if (isDebug) {
                    LOGGER.debug("matched {}", fileName);
                }
                return true;
            }
            if (unzipIsRequested && fileName.endsWith(ZIP_SUFFIX) && matchFoundInZip(part)) {
                return true;
            }
        }
    }
    
    // if no matching attachment was found and at least one exception was catched rethrow it up
    if (anException != null) {
        throw anException;
    }
    
    return false;
}