Java Code Examples for javax.mail.Part#getContent()
The following examples show how to use
javax.mail.Part#getContent() .
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: AbstractTransport.java From javamail with Apache License 2.0 | 6 votes |
/** * Recursive find body parts and save them to HashMap */ private static void checkPartForTextType(HashMap<String, Collection<String>> bodies, Part part) throws IOException, MessagingException { Object content = part.getContent(); if (content instanceof CharSequence) { String ct = part.getContentType(); Collection<String> value = bodies.get(ct); if (value != null) { value.add(content.toString()); } else { value = new LinkedList<>(); value.add(content.toString()); bodies.put(ct, value); } } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; for(int i = 0; i < mp.getCount(); i++) { checkPartForTextType(bodies, mp.getBodyPart(i)); } } }
Example 2
Source File: NoteDetailActivity.java From ImapNote2 with GNU General Public License v3.0 | 6 votes |
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 3
Source File: EMLTransformer.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
/** * 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); } } } }
Example 4
Source File: ServiceMcaCondition.java From scipio-erp with Apache License 2.0 | 6 votes |
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 ArrayList<>(); // SCIPIO: switched to ArrayList 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 ArrayList<>(); // SCIPIO: switched to ArrayList } }
Example 5
Source File: Mail.java From camunda-bpm-mail with Apache License 2.0 | 6 votes |
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 6
Source File: MimeMessageParser.java From eml-to-pdf-converter with Apache License 2.0 | 6 votes |
/** * 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; }
Example 7
Source File: MessageParser.java From translationstudio8 with GNU General Public License v2.0 | 5 votes |
/** * 获取消息附件中的文件. * @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 8
Source File: StripAttachment.java From james-project with Apache License 2.0 | 5 votes |
/** * Checks every part in this part (if it is a Multipart) for having a * filename that matches the pattern. * If the name matches: * - the file is stored (using its name) in the given directory (if directoryName is given in the mailet configuration) * and the filename is stored in 'saved' mail list attribute * - the part is removed (when removeAttachments mailet configuration property is 'all' or 'matched') * and the filename is stored in 'removed' mail list attribute * - the part filename and its content is stored in mail map attribute (if attributeName is given in the mailet configuration) * * Note: this method is recursive. * * @param part * The part to analyse. * @param mail * @return True if one of the subpart was removed * @throws Exception */ @VisibleForTesting boolean processMultipartPartMessage(Part part, Mail mail) throws MailetException { if (!isMultipart(part)) { return false; } try { Multipart multipart = (Multipart) part.getContent(); boolean atLeastOneRemoved = false; boolean subpartHasBeenChanged = false; List<BodyPart> bodyParts = MultipartUtil.retrieveBodyParts(multipart); for (BodyPart bodyPart: bodyParts) { if (isMultipart(bodyPart)) { if (processMultipartPartMessage(bodyPart, mail)) { subpartHasBeenChanged = true; } } else { if (shouldBeRemoved(bodyPart, mail)) { multipart.removeBodyPart(bodyPart); atLeastOneRemoved = true; } } } if (atLeastOneRemoved || subpartHasBeenChanged) { updateBodyPart(part, multipart); } return atLeastOneRemoved || subpartHasBeenChanged; } catch (Exception e) { LOGGER.error("Failing while analysing part for attachments (StripAttachment mailet).", e); return false; } }
Example 9
Source File: EmailUtils.java From ogham with Apache License 2.0 | 5 votes |
private static void findParts(Part part, StringBuilder structure, String indent) throws IOException, MessagingException { addPart(part, structure, indent); Object content = part.getContent(); if (content instanceof Multipart) { findParts((Multipart) content, structure, indent); } }
Example 10
Source File: EmailUtils.java From ogham with Apache License 2.0 | 5 votes |
private static <T extends Part> void findBodyParts(Part part, Predicate<Part> filter, List<T> founds, String indent) throws MessagingException { try { addPart(filter, founds, indent, part); Object content = part.getContent(); if (content instanceof Multipart) { Multipart mp = (Multipart) content; LOG.trace("{}find {}", indent, mp.getContentType()); for (int i = 0; i < mp.getCount(); i++) { findBodyParts(mp.getBodyPart(i), filter, founds, indent + " "); } } } catch (IOException e) { throw new MessagingException("Failed to access content of the mail", e); } }
Example 11
Source File: MimeMessageParser.java From eml-to-pdf-converter with Apache License 2.0 | 5 votes |
/*** * 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 12
Source File: MailUtils.java From scada with MIT License | 5 votes |
/** * ���渽�� * @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 13
Source File: MailUtils.java From scada with MIT License | 5 votes |
/** * �ж��ʼ����Ƿ�������� * @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 14
Source File: MessageParser.java From tmxeditor8 with GNU General Public License v2.0 | 5 votes |
/** * 获取消息附件中的文件. * @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: EMLTransformer.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
/** * Finds the suitable part from an multipart/alternative and appends it's text content to StringBuilder sb * * @param multipart * @param sb * @throws IOException * @throws MessagingException */ private void processAlternativeMultipart(Multipart multipart, StringBuilder sb) throws IOException, MessagingException { Part partToUse = null; for (int i = 0, n = multipart.getCount(); i < n; i++) { Part part = multipart.getBodyPart(i); if (part.getContentType().contains(MimetypeMap.MIMETYPE_TEXT_PLAIN)) { partToUse = part; break; } else if (part.getContentType().contains(MimetypeMap.MIMETYPE_HTML)) { partToUse = part; } else if (part.getContentType().contains(MimetypeMap.MIMETYPE_MULTIPART_ALTERNATIVE)) { if (part.getContent() instanceof Multipart) { processAlternativeMultipart((Multipart) part.getContent(), sb); } } } if (partToUse != null) { processPart(partToUse, sb); } }
Example 16
Source File: MessageHelper.java From FairEmail with GNU General Public License v3.0 | 5 votes |
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"); } }
Example 17
Source File: MailAccount.java From projectforge-webapp with GNU General Public License v3.0 | 4 votes |
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 |
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: AttachmentFileNameIs.java From james-project with Apache License 2.0 | 4 votes |
/** * 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; }
Example 20
Source File: Pop3Util.java From anyline with Apache License 2.0 | 4 votes |
/** * 保存附件 * * @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; }