Java Code Examples for javax.mail.Part#isMimeType()

The following examples show how to use javax.mail.Part#isMimeType() . 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: JavamailService.java    From lemon with Apache License 2.0 6 votes vote down vote up
public 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);
        }
    }
}
 
Example 2
Source File: Mail.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
protected static void processMessagePartContent(Part part, Mail mail) throws MessagingException, IOException {

    if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {

      Attachment attachment = Attachment.from(part);
      mail.attachments.add(attachment);

    } else {

      if (part.isMimeType("text/plain")) {
        mail.text = (String) part.getContent();

      } else if (part.isMimeType("text/html")) {
        mail.html = (String) part.getContent();
      }
    }
  }
 
Example 3
Source File: NoteDetailActivity.java    From ImapNote2 with GNU General Public License v3.0 6 votes vote down vote up
private void GetPart(Part message) throws Exception {
if (message.isMimeType("text/plain")) {
Log.d(TAG,"+++ isMimeType text/plain (contentType):"+message.getContentType());
} else if (message.isMimeType("multipart/*")) {
Log.d(TAG,"+++ isMimeType multipart/* (contentType):"+message.getContentType());
Object content = message.getContent();
         Multipart mp = (Multipart) content;
         int count = mp.getCount();
         for (int i = 0; i < count; i++) GetPart(mp.getBodyPart(i));
} else if (message.isMimeType("message/rfc822")) {
Log.d(TAG,"+++ isMimeType message/rfc822/* (contentType):"+message.getContentType());
GetPart((Part) message.getContent());
} else if (message.isMimeType("image/jpeg")) {
Log.d(TAG,"+++ isMimeType image/jpeg (contentType):"+message.getContentType());
} else if (message.getContentType().contains("image/")) {
Log.d(TAG,"+++ isMimeType image/jpeg (contentType):"+message.getContentType());
} else {
  Object o = message.getContent();
  if (o instanceof String) {
      Log.d(TAG,"+++ instanceof String");
  } else if (o instanceof InputStream) {
      Log.d(TAG,"+++ instanceof InputStream");
  } else Log.d(TAG,"+++ instanceof ???");
}
    }
 
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: 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 6
Source File: SubethaEmailMessage.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Method extracts file name from a message part for saving its as aa attachment. If the file name can't be extracted, it will be generated based on defaultPrefix parameter.
 * 
 * @param defaultPrefix This prefix fill be used for generating file name.
 * @param messagePart A part of message
 * @return File name.
 * @throws MessagingException
 */
private String getPartFileName(String defaultPrefix, Part messagePart) throws MessagingException
{
    String fileName = messagePart.getFileName();
    if (fileName != null)
    {
        try
        {
            fileName = MimeUtility.decodeText(fileName);
        }
        catch (UnsupportedEncodingException ex)
        {
            // Nothing to do :)
        }
    }
    else
    {
        fileName = defaultPrefix;
        if (messagePart.isMimeType(MIME_PLAIN_TEXT))
            fileName += ".txt";
        else if (messagePart.isMimeType(MIME_HTML_TEXT))
            fileName += ".html";
        else if (messagePart.isMimeType(MIME_XML_TEXT))
            fileName += ".xml";
        else if (messagePart.isMimeType(MIME_IMAGE))
            fileName += ".gif";
    }
    return fileName;
}
 
Example 7
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 8
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 9
Source File: MimeMessageParser.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
/***
 * Walk the Mime Structure recursivly and execute the callback on every part.
 * @param p mime object
 * @param initial level of current depth of the part
 * @param callback Object holding the callback function
 * @throws Exception
 */
private static void walkMimeStructure(Part p, int level, WalkMimeCallback callback) throws Exception {
	callback.walkMimeCallback(p, level);
	
	if (p.isMimeType("multipart/*")) {
		Multipart mp = (Multipart) p.getContent();
		for (int i = 0; i < mp.getCount(); i++) {
			walkMimeStructure(mp.getBodyPart(i), level + 1, callback);
		}
	}
}
 
Example 10
Source File: MessageParser.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 获取消息附件中的文件.
 * @param part
 *            Part 对象
 * @param resourceList
 *            文件的集合(每个 ResourceFileBean 对象中存放文件名和 InputStream 对象)
 * @throws MessagingException
 *             the messaging exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private void getRelatedPart(Part part, List<ResourceFileBean> resourceList) throws MessagingException, IOException {
	//验证 Part 对象的 MIME 类型是否与指定的类型匹配。
	if (part.isMimeType("multipart/related")) {
		Multipart mulContent = (Multipart) part.getContent();
		for (int j = 0, m = mulContent.getCount(); j < m; j++) {
			Part contentPart = mulContent.getBodyPart(j);
			if (!contentPart.isMimeType("text/*")) {
				String fileName = "Resource";
				//此方法返回 Part 对象的内容类型。
				String type = contentPart.getContentType();
				if (type != null) {
					type = type.substring(0, type.indexOf("/"));
				}
				fileName = fileName + "[" + type + "]";
				if (contentPart.getHeader("Content-Location") != null
						&& contentPart.getHeader("Content-Location").length > 0) {
					fileName = contentPart.getHeader("Content-Location")[0];
				}
				InputStream is = contentPart.getInputStream();
				resourceList.add(new ResourceFileBean(fileName, is));
			}
		}
	} else {
		Multipart mp = null;
		Object content = part.getContent();
		if (content instanceof Multipart) {
			mp = (Multipart) content;
		} else {
			return;
		}
		for (int i = 0, n = mp.getCount(); i < n; i++) {
			Part body = mp.getBodyPart(i);
			getRelatedPart(body, resourceList);
		}
	}
}
 
Example 11
Source File: EmailAccount.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns if the part can be handled as multipart/mixed.
 */
private boolean mimeTypeCanBeHandledAsMultiPartMixed(Part part) throws MessagingException {
    return part.isMimeType("multipart/mixed") || part.isMimeType("multipart/parallel")
            || part.isMimeType("message/rfc822")
            // as per the RFC2046 specification, other multipart subtypes are recognized as multipart/mixed
            || part.isMimeType("multipart/*");
}
 
Example 12
Source File: StripAttachment.java    From james-project with Apache License 2.0 5 votes vote down vote up
private boolean isMultipart(Part part) throws MailetException {
    try {
        return part.isMimeType(MULTIPART_MIME_TYPE);
    } catch (MessagingException e) {
        throw new MailetException("Could not retrieve contenttype of MimePart.", e);
    }
}
 
Example 13
Source File: BlueDragonMailWrapper.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private void	getParts( Part part, List<BlueDragonPartWrapper> list ) throws MessagingException, IOException{
	if ( part.isMimeType("multipart/*") ){

		Multipart mp  = (Multipart)part.getContent();
    int count     = mp.getCount();
    for (int i = 0; i < count; i++)
    	getParts( mp.getBodyPart(i), list );

  }else{
    list.add( new BlueDragonPartWrapper( part ) );
  }
}
 
Example 14
Source File: MessageParser.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 获取消息附件中的文件.
 * @param part
 *            Part 对象
 * @param resourceList
 *            文件的集合(每个 ResourceFileBean 对象中存放文件名和 InputStream 对象)
 * @throws MessagingException
 *             the messaging exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private void getRelatedPart(Part part, List<ResourceFileBean> resourceList) throws MessagingException, IOException {
	//验证 Part 对象的 MIME 类型是否与指定的类型匹配。
	if (part.isMimeType("multipart/related")) {
		Multipart mulContent = (Multipart) part.getContent();
		for (int j = 0, m = mulContent.getCount(); j < m; j++) {
			Part contentPart = mulContent.getBodyPart(j);
			if (!contentPart.isMimeType("text/*")) {
				String fileName = "Resource";
				//此方法返回 Part 对象的内容类型。
				String type = contentPart.getContentType();
				if (type != null) {
					type = type.substring(0, type.indexOf("/"));
				}
				fileName = fileName + "[" + type + "]";
				if (contentPart.getHeader("Content-Location") != null
						&& contentPart.getHeader("Content-Location").length > 0) {
					fileName = contentPart.getHeader("Content-Location")[0];
				}
				InputStream is = contentPart.getInputStream();
				resourceList.add(new ResourceFileBean(fileName, is));
			}
		}
	} else {
		Multipart mp = null;
		Object content = part.getContent();
		if (content instanceof Multipart) {
			mp = (Multipart) content;
		} else {
			return;
		}
		for (int i = 0, n = mp.getCount(); i < n; i++) {
			Part body = mp.getBodyPart(i);
			getRelatedPart(body, resourceList);
		}
	}
}
 
Example 15
Source File: EmailAccount.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
private String getTextFromPart(Part part) throws MessagingException, IOException {
    if (part.isMimeType("multipart/alternative")) {
        return getTextFromMultiPartAlternative((Multipart) part.getContent());
    } else if (part.isMimeType("multipart/digest")) {
        return getTextFromMultiPartDigest((Multipart) part.getContent());
    } else if (mimeTypeCanBeHandledAsMultiPartMixed(part)) {
        return getTextHandledAsMultiPartMixed(part);
    }

    return null;
}
 
Example 16
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 17
Source File: MailAccount.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
private void getContent(final Part msg, final StringBuffer buf) throws MessagingException, IOException
{
  if (log.isDebugEnabled() == true) {
    log.debug("CONTENT-TYPE: " + msg.getContentType());
  }
  String filename = msg.getFileName();
  if (filename != null) {
    log.debug("FILENAME: " + filename);
  }
  // Using isMimeType to determine the content type avoids
  // fetching the actual content data until we need it.
  if (msg.isMimeType("text/plain")) {
    log.debug("This is plain text");
    try {
      buf.append(msg.getContent());
    } catch (UnsupportedEncodingException ex) {
      buf.append("Unsupported charset by java mail, sorry: " + "CONTENT-TYPE=[" + msg.getContentType() + "]");
    }
  } else if (msg.isMimeType("text/html")) {
    log.debug("This is html text");
    buf.append(msg.getContent());
  } else if (msg.isMimeType("multipart/*")) {
    log.debug("This is a Multipart");
    final Multipart multiPart = (Multipart) msg.getContent();
    int count = multiPart.getCount();
    for (int i = 0; i < count; i++) {
      if (i > 0) {
        buf.append("\n----------\n");
      }
      getContent(multiPart.getBodyPart(i), buf);
    }
  } else if (msg.isMimeType("message/rfc822")) {
    log.debug("This is a Nested Message");
    buf.append(msg.getContent());
  } else {
    log.debug("This is an unknown type");
    // If we actually want to see the data, and it's not a
    // MIME type we know, fetch it and check its Java type.
    final Object obj = msg.getContent();
    if (obj instanceof String) {
      buf.append(obj);
    } else if (obj instanceof InputStream) {
      log.debug("Inputstream");
      buf.append("Attachement: ");
      if (filename != null) {
        buf.append(filename);
      } else {
        buf.append("Unsupported format (not a file).");
      }
    } else {
      log.error("Should not occur");
      buf.append("Unsupported type");
    }
  }
}
 
Example 18
Source File: EmailFormatterInbound.java    From matrix-appservice-email with GNU Affero General Public License v3.0 4 votes vote down vote up
protected List<_BridgeMessageContent> extractContent(Part p) throws MessagingException, IOException {
    if (p.isMimeType("multipart/*")) {
        log.info("Found multipart content, extracting");

        List<_BridgeMessageContent> contents = new ArrayList<>();
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            contents.addAll(extractContent(mp.getBodyPart(i)));
        }
        return contents;
    }

    if (p.isMimeType("message/rfc822")) {
        log.info("Found nested content, extracting");
        return extractContent((Part) p.getContent());
    }

    String content = p.getContent().toString();
    String[] encodings = p.getHeader("Content-Transfer-Encoding");
    String encoding = (encodings != null && encodings.length > 0) ? encodings[0] : null;

    if (StringUtils.equalsIgnoreCase("quoted-printable", encoding)) {
        try {
            // TODO actually extract the charset properly
            // TODO read RFC to know default charset
            log.info("Transfer encoding is {}, decoding", encoding);
            content = new String(QuotedPrintableCodec.decodeQuotedPrintable(content.getBytes()));
        } catch (DecoderException e) {
            log.warn("Content transfer encoding is set to {} but enable to decode: {}", encoding, e.getMessage());
        }
    }

    if (p.isMimeType(MimeTypeUtils.TEXT_PLAIN_VALUE)) {
        log.info("Found plain text content");
        return Collections.singletonList(new BridgeMessageTextContent(content, encoding));
    }

    if (p.isMimeType(MimeTypeUtils.TEXT_HTML_VALUE)) {
        log.info("Found HTML content");
        return Collections.singletonList(new BridgeMessageHtmlContent(content, encoding));
    }

    return Collections.emptyList();
}
 
Example 19
Source File: EmailUtils.java    From ogham with Apache License 2.0 3 votes vote down vote up
/**
 * Indicates if the part contains text (either plain text or html). It is
 * checked using Content-Type (either "text/*", "application/html" or
 * "application/xhtml").
 * 
 * @param part
 *            the part to check
 * @return true if it is text
 */
public static boolean isTextualContent(Part part) {
	try {
		return part.isMimeType("text/*") || part.isMimeType("application/html") || part.isMimeType("application/xhtml");
	} catch (MessagingException e) {
		throw new MessagingRuntimeException("Failed to retrieve Content-Type of part", e);
	}
}
 
Example 20
Source File: EmailUtils.java    From ogham with Apache License 2.0 3 votes vote down vote up
/**
 * Indicates if a part is a multipart (its Content-Type starts with
 * "multipart/").
 * 
 * @param part
 *            the part to check
 * @return true if a multipart
 */
public static boolean isMultipart(Part part) {
	try {
		return part.isMimeType("multipart/*");
	} catch (MessagingException e) {
		throw new MessagingRuntimeException("Failed to retrieve Content-Type of part", e);
	}
}