private static void readMultiPart(MultipartResult res, MimeMultipart multipart) throws MessagingException { for (int i = 0; i < multipart.getCount(); i++) { BodyPart part = multipart.getBodyPart(i); try { if (part.isMimeType("image/*") || part.isMimeType("application/*")) continue; Object content = null; try { content = part.getContent(); } catch (UnsupportedEncodingException ex) { String body = ConvertUtil.inputStreamToString(part.getInputStream()); res.body = body; continue; } if (part.isMimeType("text/plain")) { res.body = content.toString(); } else if (part.isMimeType("text/*")) { res.bodyHtml = content.toString(); } else if (content instanceof MimeMultipart) { readMultiPart(res, (MimeMultipart) content); } else if (content instanceof IMAPNestedMessage) { res.body = getBody((IMAPNestedMessage) content); return; } else if (content instanceof InputStream) { if (content instanceof IMAPInputStream) { String body = ConvertUtil.inputStreamToString(part.getInputStream()); res.body = body; } else System.out.println( String.format( "Ignoring binary content in mail: %s [%s]", part.getContentType(), content.getClass())); } else if (part.isMimeType("message/*")) { res.body = content.toString(); } else { System.out.println( String.format( "Unknown content type in mail: %s [%s]", part.getContentType(), content.getClass())); } } catch (IllegalStateException ex) { System.out.println( String.format("Could not read contents in mail: %s", part.getContentType())); } catch (UnsupportedDataTypeException ex) { System.out.println( String.format("Could not read contents in mail: %s", part.getContentType())); } catch (FolderClosedException ex) { throw ex; } catch (Throwable ex) { System.out.println( String.format("Error while reading mail part: %s", part.getClass().toString())); } } }
public void saveEmailFiles(HttpServletRequest request, HttpServletResponse response, 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 != null) { if (fileName.toLowerCase().indexOf("gb2312") != -1 || fileName.toLowerCase().indexOf("gbk") != -1) { fileName = MimeUtility.decodeText(fileName); } if (request.getHeader("User-Agent").contains("Firefox")) { response.addHeader("content-disposition", "attachment;filename=" + fileName); } else if (request.getHeader("User-Agent").contains("MSIE")) { response.addHeader( "content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8")); } System.out.println("saveFile1"); saveFile(response, fileName, mpart.getInputStream()); } } else if (mpart.isMimeType("multipart/*")) { saveEmailFiles(request, response, mpart); } else { fileName = mpart.getFileName(); if (fileName != null) { if (fileName.toLowerCase().indexOf("gb2312") != -1 || fileName.toLowerCase().indexOf("gbk") != -1) { fileName = MimeUtility.decodeText(fileName); } if (request.getHeader("User-Agent").contains("Firefox")) { response.addHeader("content-disposition", "attachment;filename=" + fileName); } else if (request.getHeader("User-Agent").contains("MSIE")) { response.addHeader( "content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8")); } System.out.println("saveFile2"); saveFile(response, fileName, mpart.getInputStream()); } } } } else if (part.isMimeType("message/rfc822")) { saveEmailFiles(request, response, (Part) part.getContent()); } }
/** * 对复杂邮件的解析 * * @param multipart * @throws MessagingException * @throws IOException */ public static void parseMultipart(Multipart multipart) throws MessagingException, IOException { int count = multipart.getCount(); System.out.println("couont = " + count); for (int idx = 0; idx < count; idx++) { BodyPart bodyPart = multipart.getBodyPart(idx); System.out.println(bodyPart.getContentType()); if (bodyPart.isMimeType("text/plain")) { System.out.println("plain................." + bodyPart.getContent()); } else if (bodyPart.isMimeType("text/html")) { System.out.println("html..................." + bodyPart.getContent()); } else if (bodyPart.isMimeType("multipart/*")) { Multipart mpart = (Multipart) bodyPart.getContent(); parseMultipart(mpart); } else if (bodyPart.isMimeType("application/octet-stream")) { String disposition = bodyPart.getDisposition(); System.out.println(disposition); if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) { String fileName = bodyPart.getFileName(); InputStream is = bodyPart.getInputStream(); copy(is, new FileOutputStream("D:\\" + fileName)); } } } }
@POST @Path("multipart/form-data") @Consumes("multipart/form-data") public Object multipartPost(@QueryParam("attrNo") int attrNo, Multipart multipart) throws MessagingException, IOException { final BodyPart bodyPart = multipart.getBodyPart(attrNo); return bodyPart.getInputStream(); }
private void writePartAsFile(Session session, BodyPart part, String nodeName, Node parentNode) throws RepositoryException, MessagingException, IOException { Node fileNode = parentNode.addNode(nodeName, "nt:file"); Node resourceNode = fileNode.addNode("jcr:content", "nt:resource"); resourceNode.setProperty("jcr:mimeType", part.getContentType()); resourceNode.setProperty( "jcr:data", session.getValueFactory().createValue(part.getInputStream())); resourceNode.setProperty("jcr:lastModified", Calendar.getInstance()); }
private void createChildNodeForPart(Session session, int index, BodyPart part, Node message) throws RepositoryException, MessagingException, IOException { String childName = String.format("part%1$03d", index); if (part.getContentType().toLowerCase().startsWith("multipart/")) { Node childNode = message.addNode(childName); writePartPropertiesToNode(part, childNode); MimeMultipart multi = new MimeMultipart(new SMTPDataSource(part.getContentType(), part.getInputStream())); writeMultipartToNode(session, childNode, multi); return; } if (!isTextType(part)) { writePartAsFile(session, part, childName, message); return; } Node childNode = message.addNode(childName); writePartPropertiesToNode(part, childNode); childNode.setProperty( MessageConstants.PROP_SAKAI_BODY, IOUtils.toString(part.getInputStream())); }
public String getPartRawText(String index) { BodyPart part = getPart(index); if (part != null) { try { return getTextFromStream(part.getInputStream()); } catch (Exception e) { Debug.logError(e, module); return null; } } else { return null; } }
public ByteBuffer getPartByteBuffer(String index) { BodyPart part = getPart(index); if (part != null) { try { InputStream stream = part.getInputStream(); return getByteBufferFromStream(stream); } catch (Exception e) { Debug.logError(e, module); return null; } } else { return null; } }
@Override public void processInputStream(InputStream is) throws Exception { try { MimeMultipart multiPart = new MimeMultipart(new ByteArrayDataSource(is, MULTI_PART_MIME_TYPE)); int count = multiPart.getCount(); for (int part = 0; part < count; part++) { BodyPart body = multiPart.getBodyPart(part); if (body.isMimeType(OUTPUT_MIME_TYPE)) { this.inputStream = body.getInputStream(); break; } } } catch (Exception e) { this.inputStream = getErrorResponseStream(); } }
public static Blob readBlob(HttpServletRequest request, BodyPart part) throws MessagingException, IOException { String ctype = part.getContentType(); String fname = part.getFileName(); InputStream pin = part.getInputStream(); final File tmp = File.createTempFile("nx-automation-upload-", ".tmp"); FileUtils.copyToFile(pin, tmp); Blob blob = Blobs.createBlob(tmp, ctype, null, fname); RequestContext.getActiveContext(request) .addRequestCleanupHandler( new RequestCleanupHandler() { @Override public void cleanup(HttpServletRequest req) { tmp.delete(); } }); return blob; }
// 读取邮件内容 @SuppressWarnings({"rawtypes", "unchecked"}) public Map readMail(String id) throws Exception { Map map = new HashMap(); // 找到目标邮件 Message readmsg = findMail(msg, id); // 读取邮件标题 map.put("subject", readmsg.getSubject()); // 读取发件人 map.put("sender", MimeUtility.decodeText(readmsg.getFrom()[0].toString())); map.put("attach", ""); // 取得邮件内容 if (readmsg.isMimeType("text/*")) { map.put("content", readmsg.getContent().toString()); } else { System.out.println("this is not a text mail"); Multipart mp = (Multipart) readmsg.getContent(); if (mp == null) { System.out.println("the content is null"); } else System.out.println("--------------------------multipart:" + mp.toString()); BodyPart part = null; String disp = null; StringBuffer result = new StringBuffer(); // 遍历每个Miltipart对象 for (int j = 0; j < mp.getCount(); j++) { part = mp.getBodyPart(j); disp = part.getDisposition(); // 如果有附件 if (disp != null && (disp.equals(Part.ATTACHMENT) || disp.equals(Part.INLINE))) { // 取得附件文件名 String filename = MimeUtility.decodeText(part.getFileName()); // 解决中文附件名的问题 map.put("attach", filename); // 下载附件 InputStream in = part.getInputStream(); // 附件输入流 if (attachFile.isDownload(filename)) attachFile.choicePath(filename, in); // // 下载附件 } else { // 显示复杂邮件正文内容 result.append(getPart(part, j, 1)); } } map.put("content", result.toString()); } return map; }
@Test public void testSmtpServerReceiveMultipart() throws Exception { assertEquals(0, greenMail.getReceivedMessages().length); String subject = GreenMailUtil.random(); String body = GreenMailUtil.random(); GreenMailUtil.sendAttachmentEmail( "*****@*****.**", "*****@*****.**", subject, body, new byte[] {0, 1, 2}, "image/gif", "testimage_filename", "testimage_description", ServerSetupTest.SMTP); greenMail.waitForIncomingEmail(1500, 1); Message[] emails = greenMail.getReceivedMessages(); assertEquals(1, emails.length); assertEquals(subject, emails[0].getSubject()); Object o = emails[0].getContent(); assertTrue(o instanceof MimeMultipart); MimeMultipart mp = (MimeMultipart) o; assertEquals(2, mp.getCount()); BodyPart bp; bp = mp.getBodyPart(0); assertEquals(body, GreenMailUtil.getBody(bp).trim()); bp = mp.getBodyPart(1); assertEquals("AAEC", GreenMailUtil.getBody(bp).trim()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); GreenMailUtil.copyStream(bp.getInputStream(), bout); byte[] gif = bout.toByteArray(); for (int i = 0; i < gif.length; i++) { assertEquals(i, gif[i]); } }
private AttachedFileValue createAttachedFileValue(Date sentDate, BodyPart part) throws MessagingException, IOException { // Create attachment ValueBuilder<AttachedFileValue> attachmentBuilder = module.valueBuilderFactory().newValueBuilder(AttachedFileValue.class); AttachedFileValue prototype = attachmentBuilder.prototype(); // check contentType and fetch just the first part if necessary String contentType = ""; if (part.getContentType().indexOf(';') == -1) contentType = part.getContentType(); else contentType = part.getContentType().substring(0, part.getContentType().indexOf(';')); prototype.mimeType().set(contentType); prototype.modificationDate().set(sentDate); String fileName = part.getFileName(); prototype.name().set(fileName == null ? "Nofilename" : MimeUtility.decodeText(fileName)); prototype.size().set((long) part.getSize()); InputStream inputStream = part.getInputStream(); String id = attachmentStore.storeAttachment(Inputs.byteBuffer(inputStream, 4096)); String uri = "store:" + id; prototype.uri().set(uri); return attachmentBuilder.newInstance(); }
@Override public Object unmarshal(Exchange exchange, InputStream stream) throws IOException, MessagingException { MimeBodyPart mimeMessage; String contentType; Message camelMessage; Object content = null; if (headersInline) { mimeMessage = new MimeBodyPart(stream); camelMessage = exchange.getOut(); MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true); contentType = mimeMessage.getHeader(CONTENT_TYPE, null); // write the MIME headers not generated by javamail as Camel headers Enumeration<?> headersEnum = mimeMessage.getNonMatchingHeaders(STANDARD_HEADERS); while (headersEnum.hasMoreElements()) { Object ho = headersEnum.nextElement(); if (ho instanceof Header) { Header header = (Header) ho; camelMessage.setHeader(header.getName(), header.getValue()); } } } else { // check if this a multipart at all. Otherwise do nothing contentType = exchange.getIn().getHeader(CONTENT_TYPE, String.class); if (contentType == null) { return stream; } try { ContentType ct = new ContentType(contentType); if (!ct.match("multipart/*")) { return stream; } } catch (ParseException e) { LOG.warn("Invalid Content-Type " + contentType + " ignored"); return stream; } camelMessage = exchange.getOut(); MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOHelper.copyAndCloseInput(stream, bos); InternetHeaders headers = new InternetHeaders(); extractHeader(CONTENT_TYPE, camelMessage, headers); extractHeader(MIME_VERSION, camelMessage, headers); mimeMessage = new MimeBodyPart(headers, bos.toByteArray()); bos.close(); } DataHandler dh; try { dh = mimeMessage.getDataHandler(); if (dh != null) { content = dh.getContent(); contentType = dh.getContentType(); } } catch (MessagingException e) { LOG.warn("cannot parse message, no unmarshalling done"); } if (content instanceof MimeMultipart) { MimeMultipart mp = (MimeMultipart) content; content = mp.getBodyPart(0); for (int i = 1; i < mp.getCount(); i++) { BodyPart bp = mp.getBodyPart(i); DefaultAttachment camelAttachment = new DefaultAttachment(bp.getDataHandler()); @SuppressWarnings("unchecked") Enumeration<Header> headers = bp.getAllHeaders(); while (headers.hasMoreElements()) { Header header = headers.nextElement(); camelAttachment.addHeader(header.getName(), header.getValue()); } camelMessage.addAttachmentObject(getAttachmentKey(bp), camelAttachment); } } if (content instanceof BodyPart) { BodyPart bp = (BodyPart) content; camelMessage.setBody(bp.getInputStream()); contentType = bp.getContentType(); if (contentType != null && !DEFAULT_CONTENT_TYPE.equals(contentType)) { camelMessage.setHeader(CONTENT_TYPE, contentType); ContentType ct = new ContentType(contentType); String charset = ct.getParameter("charset"); if (charset != null) { camelMessage.setHeader(Exchange.CONTENT_ENCODING, MimeUtility.javaCharset(charset)); } } } else { // If we find no body part, try to leave the message alone LOG.info("no MIME part found"); } return camelMessage; }
@Override public Object evaluate() throws TMLExpressionException { Binary b = (Binary) getOperand(0); DataSource ds = new BinaryDataSource(b); Navajo result = NavajoFactory.getInstance().createNavajo(); Message mail = NavajoFactory.getInstance().createMessage(result, "Mail"); result.addMessage(mail); Message parts = NavajoFactory.getInstance().createMessage(result, "Parts", Message.MSG_TYPE_ARRAY); mail.addMessage(parts); try { MimeMultipart mmp = getMultipartMessage(ds); if (mmp != null) { for (int i = 0; i < mmp.getCount(); i++) { BodyPart bp = mmp.getBodyPart(i); String type = bp.getContentType(); Binary partBinary = new Binary(bp.getInputStream(), false); if (i == 0) { // Property content = NavajoFactory.getInstance().createProperty(result, "Content", // Property.BINARY_PROPERTY, null, 0,"",Property.DIR_OUT); Property mimeType = NavajoFactory.getInstance() .createProperty( result, "ContentType", Property.STRING_PROPERTY, type, 0, "", Property.DIR_OUT); // mail.addProperty(content); mail.addProperty(mimeType); // content.setAnyValue(partBinary); partBinary.setMimeType(type); } Message element = parts.addElement( NavajoFactory.getInstance() .createMessage(result, "Parts", Message.MSG_TYPE_ARRAY_ELEMENT)); Property content = NavajoFactory.getInstance() .createProperty( result, "Content", Property.BINARY_PROPERTY, null, 0, "", Property.DIR_OUT); element.addProperty(content); Property mimeType = NavajoFactory.getInstance() .createProperty( result, "ContentType", Property.STRING_PROPERTY, type, 0, "", Property.DIR_OUT); element.addProperty(mimeType); content.setAnyValue(partBinary); partBinary.setMimeType(type); content.addSubType("browserMime=" + type); } } else { String type = b.guessContentType(); MimeMessage mm = new MimeMessage(Session.getDefaultInstance(new Properties()), b.getDataAsStream()); // mm.get Binary body = new Binary(mm.getInputStream(), false); // mm.getC Message element = parts.addElement( NavajoFactory.getInstance() .createMessage(result, "Parts", Message.MSG_TYPE_ARRAY_ELEMENT)); Property content = NavajoFactory.getInstance() .createProperty( result, "Content", Property.BINARY_PROPERTY, null, 0, "", Property.DIR_OUT); element.addProperty(content); Property mimeType = NavajoFactory.getInstance() .createProperty( result, "ContentType", Property.STRING_PROPERTY, type, 0, "", Property.DIR_OUT); Property messageMimeType = NavajoFactory.getInstance() .createProperty( result, "ContentType", Property.STRING_PROPERTY, type, 0, "", Property.DIR_OUT); mail.addProperty(messageMimeType); element.addProperty(mimeType); content.setAnyValue(body); b.setMimeType(mm.getContentType()); content.addSubType("browserMime=" + type); } return result; } catch (MessagingException e) { logger.error("Error: ", e); } catch (IOException e) { logger.error("Error: ", e); } return null; }
@Override public ExecutionRequest readFrom( Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3, MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException { ExecutionRequest req = null; try { List<String> ctypes = headers.get("Content-Type"); String ctype = ctypes.get(0); // we need to copy first the stream into a file otherwise it may // happen that // javax.mail fail to receive some parts - I am not sure why - // perhaps the stream is no more available when javax.mail need it? File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp"); FileUtils.copyToFile(in, tmp); // get the input from the saved file in = new SharedFileInputStream(tmp); try { MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype)); BodyPart part = mp.getBodyPart(0); // use content ids InputStream pin = part.getInputStream(); JsonParser jp = factory.createJsonParser(pin); req = JsonRequestReader.readRequest(jp, headers, getCoreSession()); int cnt = mp.getCount(); if (cnt == 2) { // a blob req.setInput(readBlob(request, mp.getBodyPart(1))); } else if (cnt > 2) { // a blob list BlobList blobs = new BlobList(); for (int i = 1; i < cnt; i++) { blobs.add(readBlob(request, mp.getBodyPart(i))); } req.setInput(blobs); } else { log.error("Not all parts received."); for (int i = 0; i < cnt; i++) { log.error( "Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> " + mp.getBodyPart(i).getContentType()); } throw WebException.newException( new IllegalStateException("Received only " + cnt + " part in a multipart request")); } } finally { try { in.close(); } catch (IOException e) { // do nothing } tmp.delete(); } } catch (MessagingException | IOException e) { throw WebException.newException("Failed to parse multipart request", e); } return req; }