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

The following examples show how to use javax.mail.BodyPart#getContentType() . 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: AssertAttachment.java    From ogham with Apache License 2.0 6 votes vote down vote up
private static void assertEquals(ExpectedAttachment expected, BodyPart attachment, AssertionRegistry registry) throws Exception {
	// @formatter:off
	String prefix = "attachment named '" + expected.getName() + "'" + (attachment==null ? " (/!\\ not found)" : "");
	String contentType = attachment == null || attachment.getContentType()==null ? null : attachment.getContentType();
	registry.register(() -> Assert.assertTrue(prefix + " mimetype should match '" + expected.getMimetype() + "' but was " + (contentType==null ? "null" : "'" + contentType + "'"),
			contentType!=null && expected.getMimetype().matcher(contentType).matches()));
	registry.register(() -> Assert.assertEquals(prefix + " description should be '" + expected.getDescription() + "'", 
			expected.getDescription(),
			attachment == null ? null : attachment.getDescription()));
	registry.register(() -> Assert.assertEquals(prefix + " disposition should be '" + expected.getDisposition() + "'", 
			expected.getDisposition(),
			attachment == null ? null : attachment.getDisposition()));
	registry.register(() -> Assert.assertArrayEquals(prefix + " has invalid content", 
			expected.getContent(), 
			attachment == null ? null : getContent(attachment)));
	// @formatter:on
}
 
Example 2
Source File: MultipartMimeUtils.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the text content for a {@link BodyPart}, assuming the default
 * encoding.
 */
public static String getTextContent(BodyPart part) throws MessagingException, IOException {
  ContentType contentType = new ContentType(part.getContentType());
  String charset = contentType.getParameter("charset");
  if (charset == null) {
    // N.B.(schwardo): The MIME spec doesn't seem to provide a
    // default charset, but the default charset for HTTP is
    // ISO-8859-1.  That seems like a reasonable default.
    charset = "ISO-8859-1";
  }

  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ByteStreams.copy(part.getInputStream(), baos);
  try {
    return new String(baos.toByteArray(), charset);
  } catch (UnsupportedEncodingException ex) {
    return new String(baos.toByteArray());
  }
}
 
Example 3
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 4
Source File: MimeMessageWrapper.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public String getPartContentType(String index) {
    BodyPart part = getPart(index);
    if (part != null) {
        try {
            return part.getContentType();
        } catch (MessagingException e) {
            Debug.logError(e, module);
            return null;
        }
    }
    return null;
}
 
Example 5
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 6
Source File: MailUtils.java    From scada with MIT License 5 votes vote down vote up
/** 
 * ���渽�� 
 * @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); 
    } 
}
 
Example 7
Source File: ZhilianEmailResumeParser.java    From job with MIT License 5 votes vote down vote up
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);
}
 
Example 8
Source File: Pop3Util.java    From anyline with Apache License 2.0 4 votes vote down vote up
/** 
 * 保存附件 
 *  
 * @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; 
}
 
Example 9
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;
        }
 
Example 10
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);
  }
}