/** * 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); } } } }
/** * 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 ""; }
/** * 【保存附件】 */ public void saveAttachMent(Part part) throws Exception { String fileName = ""; if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart mpart = mp.getBodyPart(i); String disposition = mpart.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition .equals(Part.INLINE)))) { fileName = mpart.getFileName(); if (fileName.toLowerCase().indexOf("gb2312") != -1) { fileName = MimeUtility.decodeText(fileName); } saveFile(fileName, mpart.getInputStream()); } else if (mpart.isMimeType("multipart/*")) { saveAttachMent(mpart); } else { fileName = mpart.getFileName(); if ((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") != -1)) { fileName = MimeUtility.decodeText(fileName); saveFile(fileName, mpart.getInputStream()); } } } } else if (part.isMimeType("message/rfc822")) { saveAttachMent((Part) part.getContent()); } }
/** * ������ */ private void handleAttachments(Message message, Part part) throws Exception { if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart bp = mp.getBodyPart(i); String disposition = bp.getDisposition(); if (disposition != null && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) { saveFile(message, bp); } else if (bp.isMimeType("multipart/*")) { handleAttachments(message, (Part) part.getContent()); } else { saveFile(message, bp); } } } else if (part.isMimeType("message/rfc822")) { handleAttachments(message, (Part) part.getContent()); } }
/** * 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; }
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); } } }
/** * 判断此邮件是否包含附件 */ public boolean isContainAttach(Part part) throws Exception { boolean attachflag = false; String contentType = part.getContentType(); if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart mpart = mp.getBodyPart(i); String disposition = mpart.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition .equals(Part.INLINE)))) attachflag = true; else if (mpart.isMimeType("multipart/*")) { attachflag = isContainAttach((Part) mpart); } else { String contype = mpart.getContentType(); if (contype.toLowerCase().indexOf("application") != -1) attachflag = true; if (contype.toLowerCase().indexOf("name") != -1) attachflag = true; } } } else if (part.isMimeType("message/rfc822")) { attachflag = isContainAttach((Part) part.getContent()); } return attachflag; }
/** * Récupération d'une pièce jointe d'un mail * @param part : Corps du mail (Bodypart) * @return * @throws Exception */ private static Map<String, InputStream> getAttachments(BodyPart part) throws Exception { Map<String, InputStream> result = new HashMap<String, InputStream>(); Object content = part.getContent(); if (content instanceof InputStream || content instanceof String) { if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotBlank(part.getFileName())) { result.put(part.getFileName(), part.getInputStream()); return result; } else { return new HashMap<String, InputStream>(); } } if (content instanceof Multipart) { Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); result.putAll(getAttachments(bodyPart)); } } return result; }
private List<String> getBodyText(Part part) throws MessagingException, IOException { Object c = part.getContent(); if (c instanceof String) { return UtilMisc.toList((String) c); } else if (c instanceof Multipart) { List<String> textContent = new LinkedList<String>(); int count = ((Multipart) c).getCount(); for (int i = 0; i < count; i++) { BodyPart bp = ((Multipart) c).getBodyPart(i); textContent.addAll(this.getBodyText(bp)); } return textContent; } else { return new LinkedList<String>(); } }
private static TreeMap<String, InputStream> getAttachments(BodyPart part) throws Exception { TreeMap<String, InputStream> result = new TreeMap<>(); Object content = part.getContent(); if (content instanceof InputStream || content instanceof String) { if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotBlank(part.getFileName())) { result.put(part.getFileName(), part.getInputStream()); return result; } else { return new TreeMap<String, InputStream>(); } } if (content instanceof Multipart) { Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); result.putAll(getAttachments(bodyPart)); } } return result; }
/** * �ж��ʼ����Ƿ�������� * @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; }
/** * ���渽�� * @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); } }
/** * 判断邮件中是否包含附件 * @param msg 邮件内容 * @return 邮件中存在附件返回true,不存在返回false * @throws MessagingException * @throws IOException */ 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; }
/** * 获得邮件文本内容 * @param part 邮件体 * @param content 存储邮件文本内容的字符串 * @throws MessagingException * @throws IOException */ 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); } } }
/** * 保存附件 * @param part 邮件中多个组合体中的其中一个组合体 * @param destDir 附件保存目录 * @throws UnsupportedEncodingException * @throws MessagingException * @throws FileNotFoundException * @throws IOException */ 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); //某一个邮件体也有可能是由多个邮件体组成的复杂体 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); } }
private void downloadAttachment(Part part, String folderPath) throws MessagingException, IOException { String disPosition = part.getDisposition(); String fileName = part.getFileName(); String decodedAttachmentName = null; if (fileName != null) { LOGGER.info("Attached File Name :: " + fileName); decodedAttachmentName = MimeUtility.decodeText(fileName); LOGGER.info("Decoded string :: " + decodedAttachmentName); decodedAttachmentName = Normalizer.normalize(decodedAttachmentName, Normalizer.Form.NFC); LOGGER.info("Normalized string :: " + decodedAttachmentName); int extensionIndex = decodedAttachmentName.indexOf(EXTENSION_VALUE_46); extensionIndex = extensionIndex == -1 ? decodedAttachmentName.length() : extensionIndex; File parentFile = new File(folderPath); LOGGER.info("Updating file name if any file with the same name exists. File : " + decodedAttachmentName); decodedAttachmentName = FileUtils.getUpdatedFileNameForDuplicateFile(decodedAttachmentName.substring(0, extensionIndex), parentFile, -1) + decodedAttachmentName.substring(extensionIndex); LOGGER.info("Updated file name : " + decodedAttachmentName); } if (disPosition != null && disPosition.equalsIgnoreCase(Part.ATTACHMENT)) { File file = new File(folderPath + File.separator + decodedAttachmentName); file.getParentFile().mkdirs(); saveEmailAttachment(file, part); } }
public static void saveEmailAttachment(final File saveFile, final Part part) throws FileNotFoundException, IOException, MessagingException { InputStream inputStream = null; try { if (part != null) { inputStream = part.getInputStream(); if (inputStream != null) { FileUtils.writeFileViaStream(saveFile, inputStream); } } } finally { try { if (inputStream != null) { inputStream.close(); } } catch (final IOException e) { LOGGER.error("Error while closing the input stream.", e); } } }
private void parsePart(Part part) throws Exception { if (part.isMimeType("text/*")) { content.append((String) part.getContent()); } else if (part.isMimeType("multipart/*")) { Part p = null; Multipart multipart = (Multipart) part.getContent(); for (int i = 0; i < multipart.getCount(); i++) { p = multipart.getBodyPart(i); String disposition = p.getDisposition(); if (disposition != null && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) { attachments.add(MimeUtility.decodeText(p.getFileName())); } parsePart(p); } } else if (part.isMimeType("message/rfc822")) { parsePart((Part) part.getContent()); } }
/** * Get the String Content of a MimePart. * @param p MimePart * @return Content as String * @throws IOException * @throws MessagingException */ private static String getStringContent(Part p) throws IOException, MessagingException { Object content = null; try { content = p.getContent(); } catch (Exception e) { Logger.debug("Email body could not be read automatically (%s), we try to read it anyway.", e.toString()); // most likely the specified charset could not be found content = p.getInputStream(); } String stringContent = null; if (content instanceof String) { stringContent = (String) content; } else if (content instanceof InputStream) { stringContent = new String(ByteStreams.toByteArray((InputStream) content), "utf-8"); } return stringContent; }
/** * �����ʼ����� */ public static String getContent(Part part) throws Exception { if (part.isMimeType("text/plain")) { return (String) part.getContent(); } else if (part.isMimeType("text/html")) { return (String) part.getContent(); } else if (part.isMimeType("multipart/*")) { Multipart multipart = (Multipart) part.getContent(); String content = ""; for (int i = 0; i < multipart.getCount(); i++) { content += getContent(multipart.getBodyPart(i)); } return content; } else if (part.isMimeType("message/rfc822")) { return getContent((Part) part.getContent()); } return ""; }
public static String getFilename( Part Mess ) throws MessagingException{ // Part.getFileName() doesn't take into account any encoding that may have been // applied to the filename so in order to obtain the correct filename we // need to retrieve it from the Content-Disposition String [] contentType = Mess.getHeader( "Content-Disposition" ); if ( contentType != null && contentType.length > 0 ){ int nameStartIndx = contentType[0].indexOf( "filename=\"" ); if ( nameStartIndx != -1 ){ String filename = contentType[0].substring( nameStartIndx+10, contentType[0].indexOf( '\"', nameStartIndx+10 ) ); try { filename = MimeUtility.decodeText( filename ); return filename; } catch (UnsupportedEncodingException e) {} } } // couldn't determine it using the above, so fall back to more reliable but // less correct option return Mess.getFileName(); }
@Override public void doTag() throws IOException, JspException { PageContext pageContext = (PageContext)getJspContext(); JspWriter out = pageContext.getOut(); try { // make an HTML link for each attachment List<Part> parts = email.getParts(); for (int partIndex=0; partIndex<parts.size(); partIndex++) { Part part = parts.get(partIndex); if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { String filename = part.getFileName(); out.println("<a href=\"showAttachment?messageID=" + email.getMessageID() + "&folder=" + folder + "&part=" + partIndex + "\">" + filename + "</a> (" + Util.getHumanReadableSize(part) + ") <br/>"); } } } catch (MessagingException e) { throw new JspException("Can't parse email.", e); } }
/** * Returns the <code>Part</code> whose <code>content</code> * should be displayed inline. * @throws MessagingException * @throws IOException */ private Part getMainTextPart() throws MessagingException, IOException { List<Part> parts = getParts(); Part mostPreferable = this; for (Part part: parts) { String disposition = part.getDisposition(); if (!Part.ATTACHMENT.equalsIgnoreCase(disposition)) { // prefer plain text if (part.isMimeType("text/plain")) return part; else if (part.isMimeType("text/html")) mostPreferable = part; } } return mostPreferable; }
/** Returns the size of an email attachment in a user-friendly format * @throws MessagingException * @throws IOException */ public static String getHumanReadableSize(Part part) throws IOException, MessagingException { // find size in bytes InputStream inputStream = part.getInputStream(); byte[] buffer = new byte[32*1024]; long totalBytes = 0; int bytesRead; do { bytesRead = inputStream.read(buffer, 0, buffer.length); if (bytesRead > 0) totalBytes += bytesRead; } while (bytesRead > 0); // format to a string return getHumanReadableSize(totalBytes); }
private String getPlainTextMessage(Part part) throws MessagingException, IOException { if (part.isMimeType("text/plain")) { return (String) part.getContent(); } else if (part.isMimeType("multipart/*")) { Multipart multi = (Multipart) part; for (int i = 0 ; i < multi.getCount(); i++) { Part subPart = multi.getBodyPart(i); String text = getPlainTextMessage(subPart); if (text != null) return text; } } return null; }
/** * 提取html * * @param p * @return * @throws MessagingException * @throws IOException * @throws Exception */ public String dumpPart(Part p) throws MessagingException, IOException { String contentType = p.getContentType().toLowerCase(); Object o = p.getContent(); if (o instanceof String) {// 这是纯文本 if (contentType.contains(CONTENT_TYPE_TEXT_HTML)) { return (String) o; } } else if (o instanceof Multipart) {// multipart Multipart mp = (Multipart) o; int count = mp.getCount(); for (int i = 0; i < count; i++) { String result = dumpPart(mp.getBodyPart(i)); if (result != null) { return result; } } } return null; }
/** * 提取html * * @param p * @return * @throws Exception */ public String dumpPart(Part p) throws Exception { String contentType = p.getContentType().toLowerCase(); Object o = p.getContent(); if (o instanceof String) {// 这是纯文本 if (contentType.contains(CONTENT_TYPE_TEXT_HTML)) { return (String) o; } } else if (o instanceof Multipart) {// multipart Multipart mp = (Multipart) o; int count = mp.getCount(); for (int i = 0; i < count; i++) { String result = dumpPart(mp.getBodyPart(i)); if (result != null) { return result; } } } return null; }
private String processMultipart(Part part) throws IOException, MessagingException { Multipart relatedparts = (Multipart)part.getContent(); for (int j = 0; j < relatedparts.getCount(); j++) { Part rel = relatedparts.getBodyPart(j); if (rel.getDisposition() == null) { // again, if it's not an image or attachment(only those have disposition not null) if (rel.isMimeType("multipart/alternative")) { // last crawl through the alternative formats. return extractAlternativeContent(rel); } } } return null; }
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 ???"); } }
private static InputStream getInputStream( Part bodyPart) throws MessagingException { try { if (bodyPart.isMimeType("multipart/signed")) { throw new MessagingException("attempt to create signed data object from multipart content - use MimeMultipart constructor."); } return bodyPart.getInputStream(); } catch (IOException e) { throw new MessagingException("can't extract input stream: " + e); } }
private static InputStream getInputStream( Part bodyPart, int bufferSize) throws MessagingException { try { InputStream in = bodyPart.getInputStream(); if (bufferSize == 0) { return new BufferedInputStream(in); } else { return new BufferedInputStream(in, bufferSize); } } catch (IOException e) { throw new MessagingException("can't extract input stream: " + e); } }