private void rePart(Part part) throws Exception { if (part.getDisposition() != null) { String strFileNmae = MimeUtility.decodeText(part.getFileName()); // MimeUtility.decodeText解决附件名乱码问题 System.out.println("发现附件: " + MimeUtility.decodeText(part.getFileName())); System.out.println("内容类型: " + MimeUtility.decodeText(part.getContentType())); System.out.println("附件内容:" + part.getContent()); InputStream in = part.getInputStream(); // 打开附件的输入流 // 读取附件字节并存储到文件中 java.io.FileOutputStream out = new FileOutputStream(strFileNmae); int data; while ((data = in.read()) != -1) { out.write(data); } in.close(); out.close(); } else { if (part.getContentType().startsWith("text/plain")) { System.out.println("文本内容:" + part.getContent()); } else { // System.out.println("HTML内容:" + part.getContent()); } } }
/** * 保存附件 * * @param part */ public static void saveAttachFile(Part part) { try { if (part.getDisposition() == null) return; String dir = DIR; String filename = decodeText(part.getFileName()); File dirRoot = new File(dir); if (!dirRoot.exists()) { dirRoot.mkdirs(); } InputStream in = part.getInputStream(); OutputStream out = new FileOutputStream(new File(dir + File.separator + filename)); byte[] buffer = new byte[8192]; while (in.read(buffer) != -1) { out.write(buffer); } in.close(); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
/* * (non-Javadoc) * * @see javax.servlet.http.HttpServlet#service(javax.servlet.ServletRequest, * javax.servlet.ServletResponse) */ @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String messageId = request.getParameter("messageId"); String attachmentIndex = request.getParameter("attachmentIndex"); boolean isThumbnail = Boolean.valueOf(request.getParameter("thumbnail")).booleanValue(); if (messageId != null) { IMailbox mailbox = SessionManager.get().getMailbox(); Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId)); if (isThumbnail) { List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg); int index = Integer.valueOf(attachmentIndex); MimePart retrievePart = attachmentList.get(index); ContentType contentType = new ContentType(retrievePart.getContentType()); response.setContentType(contentType.getBaseType()); BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream()); OutputStream outputStream = response.getOutputStream(); writeScaledImage(bufInputStream, outputStream); bufInputStream.close(); outputStream.flush(); outputStream.close(); } else { Part imagePart = findImagePart(msg); if (imagePart != null) { ContentType contentType = new ContentType(imagePart.getContentType()); response.setContentType(contentType.getBaseType()); BufferedInputStream bufInputStream = new BufferedInputStream(imagePart.getInputStream()); OutputStream outputStream = response.getOutputStream(); byte[] inBuf = new byte[1024]; int len = 0; int total = 0; while ((len = bufInputStream.read(inBuf)) > 0) { outputStream.write(inBuf, 0, len); total += len; } bufInputStream.close(); outputStream.flush(); outputStream.close(); } } } } catch (Exception ex) { log.error(ex.getMessage(), ex); } }
/** @param multipart */ private void handleContent(Multipart multipart, String contentType) { Log.debug(this, "handleContent"); try { // String contentType=multipart.getContentType(); for (int j = 0; j < multipart.getCount(); j++) { Part part = multipart.getBodyPart(j); Log.debug(this, String.valueOf(part.getLineCount())); Log.debug(this, String.valueOf(part.getContent())); Log.debug(this, String.valueOf(part.getContentType())); if (HiltonUtility.isEmpty(contentType) || part.getContentType().indexOf(contentType) >= 0) { String disposition = part.getDisposition(); Log.debug(this, "handleContent-disposition: " + disposition); // if (disposition != null) // { InputStream inputStream = part.getInputStream(); byte[] buffer = new byte[inputStream.available()]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) > -1) // Read // bytes // until // EOF { Log.debug(this, "reading contents"); } String tmp = new String(buffer); this.bodytext.append(tmp); this.bodytext.append("\r\n"); Log.debug(this, "handleContent: " + tmp); if (inputStream != null) { try { inputStream.close(); } catch (IOException io) { Log.error(this, " error Closing InputStream" + io.getMessage()); io.printStackTrace(); } } } } // } } catch (Exception e) { Log.error(this, e.getMessage()); e.printStackTrace(); } }
private static Attachment saveAttachment(Part partToAttach, Resource container) throws MessagingException, IOException, NoSuchAlgorithmException { Attachment attach = new Attachment(); String fileName = MimeUtility.decodeText(partToAttach.getFileName()); attach.store(partToAttach.getInputStream(), fileName, container); if (!attach.mimeType.equalsIgnoreCase(partToAttach.getContentType())) { Logger.info( "The email says the content type is '" + partToAttach.getContentType() + "' but Yobi determines it is '" + attach.mimeType + "'"); } return attach; }
public static InputStream getAttachment(Part part, String filename) { try { if (filename.equals(part.getFileName())) return part.getInputStream(); if (part.getContentType().toLowerCase().startsWith("multipart")) { MimeMultipart multipart; multipart = (MimeMultipart) part.getContent(); int count = multipart.getCount(); for (int i = 0; i < count; i++) { InputStream in = getAttachment(multipart.getBodyPart(i), filename); if (in != null) return in; } } } catch (Throwable ex) { throw new RuntimeException(ex); } return null; }
private void extractPart(final Part part) throws MessagingException, IOException { if (part.getContent() instanceof Multipart) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { extractPart(mp.getBodyPart(i)); } return; } if (part.getContentType().startsWith("text/html")) { if (bodytext == null) { bodytext = (String) part.getContent(); } else { bodytext = bodytext + "<HR/>" + (String) part.getContent(); } } else if (!part.getContentType().startsWith("text/plain")) { Attachment attachment = new Attachment(); attachment.setContenttype(part.getContentType()); attachment.setFilename(part.getFileName()); InputStream in = part.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int count = 0; while ((count = in.read(buffer)) >= 0) bos.write(buffer, 0, count); in.close(); attachment.setContent(bos.toByteArray()); attachments.add(attachment); } if (!StringUtils.isNull(bodytext) && bodytext.indexOf("Original Message") > -1) { subBody = bodytext.substring(0, bodytext.indexOf("Original Message")); } else if (!StringUtils.isNull(bodytext) && bodytext.indexOf(", \"[email protected]\" <*****@*****.**> wrote:") > -1) { String tempstr = bodytext.substring( 0, bodytext.indexOf(", \"[email protected]\" <*****@*****.**> wrote:")); subBody = tempstr.substring(0, tempstr.lastIndexOf("On")); } }
/** * Save attachment. * * @param part * @param attachList * @throws MessagingException * @throws IOException */ protected void saveAttachment(Part part, List<Attachment> attachList) throws MessagingException, IOException { // generate a new file name with unique UUID. String fileName = part.getFileName(); fileName = MimeUtility.decodeText(fileName); Attachment attachment = new Attachment(); attachment.setFileName(fileName); UUID uuid = UUID.randomUUID(); String prefix = fileName.substring(0, fileName.lastIndexOf(".") + 1); String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); String tempDir = System.getProperty("java.io.tmpdir"); String filePath = tempDir + prefix + uuid + "." + suffix; int fileSize = part.getSize(); attachment.setFilePath(filePath); attachment.setFileType(suffix); attachment.setFileSize(fileSize); attachList.add(attachment); this.saveFile(filePath, part.getInputStream()); }
private void salvaUnFichero(Part unaParte, Mensaje myMensaje) throws MailException { FileOutputStream fichero; try { fichero = new FileOutputStream("./" + unaParte.getFileName()); // TODO VER EL TEMA DE CAMBIAR LA UBICACION DEL PATH myMensaje.agregarPathAdjunto("./" + unaParte.getFileName()); InputStream imagen = unaParte.getInputStream(); byte[] bytes = new byte[1000]; int leidos = 0; while ((leidos = imagen.read(bytes)) > 0) { fichero.write(bytes, 0, leidos); } } catch (FileNotFoundException e) { throw new MailException("Archivo no encontrado", e); } catch (MessagingException e) { throw new MailException("Archivo no encontrado", e); } catch (IOException e) { throw new MailException("Error al escribir", e); } }
public static void dumpPart(Part p, biz.systempartners.claims.ClaimsViewer claimsViewer) throws Exception { if (p instanceof Message) dumpEnvelope((Message) p); /** * Dump input stream .. * * <p>InputStream is = p.getInputStream(); // If "is" is not already buffered, wrap a * BufferedInputStream // around it. if (!(is instanceof BufferedInputStream)) is = new * BufferedInputStream(is); int c; while ((c = is.read()) != -1) System.out.write(c); */ String ct = p.getContentType(); try { pr("CONTENT-TYPE: " + (new ContentType(ct)).toString()); } catch (ParseException pex) { pr("BAD CONTENT-TYPE: " + ct); } String filename = p.getFileName(); if (filename != null) pr("FILENAME: " + filename); /* * Using isMimeType to determine the content type avoids * fetching the actual content data until we need it. */ if (p.isMimeType("text/plain")) { pr("This is plain text"); pr("---------------------------"); if (!showStructure && !saveAttachments) System.out.println((String) p.getContent()); } else if (p.isMimeType("multipart/*")) { pr("This is a Multipart"); pr("---------------------------"); Multipart mp = (Multipart) p.getContent(); level++; int count = mp.getCount(); for (int i = 0; i < count; i++) dumpPart(mp.getBodyPart(i), claimsViewer); level--; } else if (p.isMimeType("message/rfc822")) { pr("This is a Nested Message"); pr("---------------------------"); level++; dumpPart((Part) p.getContent(), claimsViewer); level--; } else { if (!showStructure && !saveAttachments) { /* * If we actually want to see the data, and it's not a * MIME type we know, fetch it and check its Java type. */ Object o = p.getContent(); if (o instanceof String) { pr("This is a string"); pr("---------------------------"); System.out.println((String) o); } else if (o instanceof InputStream) { pr("This is just an input stream"); pr("---------------------------"); InputStream is = (InputStream) o; int c; while ((c = is.read()) != -1) System.out.write(c); } else { pr("This is an unknown type"); pr("---------------------------"); pr(o.toString()); } } else { // just a separator pr("---------------------------"); } } /* * If we're saving attachments, write out anything that * looks like an attachment into an appropriately named * file. Don't overwrite existing files to prevent * mistakes. */ if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) { String disp = p.getDisposition(); // many mailers don't include a Content-Disposition if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) { if (filename == null) filename = "Attachment" + attnum++; pr("Saving attachment to file " + filename); try { File f = new File(System.getProperty("user.dir"), filename); /* if (f.exists()) // XXX - could try a series of names throw new IOException("file exists");*/ OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); InputStream is = p.getInputStream(); int c; while ((c = is.read()) != -1) os.write(c); os.close(); if (p.isMimeType("text/xml") || p.isMimeType("application/octet-stream")) { processBrRequisitionFile( f, claimsViewer, claimsViewer.getInvoiceVector(), claimsViewer.getFilesVector()); } System.out.println("I have saved file [" + f.getAbsolutePath() + "]"); } catch (IOException ex) { pr("Failed to save attachment: " + ex); } pr("---------------------------"); } } }
public void service(Mail mail) throws MessagingException { System.out.println("MyAppletStarted!!!"); MimeMessage message = mail.getMessage(); String contentType = message.getContentType(); System.out.println(contentType); if (message.isMimeType("text/plain")) { try { System.out.println("Extract data"); MailAddress from = mail.getSender(); Collection<MailAddress> to = mail.getRecipients(); String suser = from.getUser(); String shost = from.getHost(); String seadr = suser + "@" + shost; String text = (String) message.getContent(); output = new FileWriter(folder + seadr + "" + (++num) + ".txt"); output.write("E-mail FROM: " + seadr + "\n"); output.write("E-mail TO: "); for (Iterator<MailAddress> iterator = to.iterator(); iterator.hasNext(); ) { output.write(iterator.next().toString() + ","); } output.write("E-mail text body: " + text); System.out.println("Changes mail-body"); message.setContent(modifyTextBody(text, key), contentType); message.setHeader(RFC2822Headers.CONTENT_TYPE, contentType); message.saveChanges(); output.close(); } catch (IOException ex) { log("Unable to get text from " + mail.getName()); } } else if (message.isMimeType("multipart/mixed") || message.isMimeType("multipart/related")) { try { // здесь надо сохранить аттачи Multipart mp = (Multipart) message.getContent(); System.out.println("PartsNum: " + mp.getCount()); for (int i = 0, n = mp.getCount(); i < n; i++) { Part part = mp.getBodyPart(i); if (part.isMimeType("text/plain")) { System.out.println("Try to modify text"); // message.setContent(modifyTextBody((String)part.getContent(),key), // part.getContentType()); // message.saveChanges(); part.setContent(modifyTextBody((String) part.getContent(), key), part.getContentType()); boolean removeBodyPart = mp.removeBodyPart((BodyPart) part); System.out.println("Removed: " + removeBodyPart); mp.addBodyPart((BodyPart) part, i); message.setContent(mp); } else { String disposition = part.getDisposition(); System.out.println("Disposition " + disposition); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) { saveFile(part.getFileName(), part.getInputStream()); System.out.println("Try to modify attache"); byte[] new_attach = this.modifyAttachments(part.getInputStream(), key); part.setContent(new_attach, part.getContentType()); part.setFileName("encrypted" + i); boolean removeBodyPart = mp.removeBodyPart((BodyPart) part); System.out.println("Removed: " + removeBodyPart); mp.addBodyPart((BodyPart) part, i); message.setContent(mp); System.out.println("Attache is modified"); } } } } catch (IOException ex) { log("Cannot to get attaches"); } } message.setHeader(RFC2822Headers.CONTENT_TYPE, contentType); message.saveChanges(); System.out.println("Ended"); }