List of usage examples for javax.mail Part getInputStream
public InputStream getInputStream() throws IOException, MessagingException;
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!/*from w w w. jav a 2 s. c o m*/ * * @param part DOCUMENT ME! * * @return DOCUMENT ME! */ private static int sizeInline(Part part) { int size = 0; try { size += IOUtils.toByteArray(part.getInputStream()).length; } catch (IOException e) { } catch (MessagingException e) { } catch (Exception e) { } return size; }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!/* w w w . ja va 2 s . c o m*/ * * @param part DOCUMENT ME! * * @return DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static BufferedReader getTextReader(Part part, String charset) throws MessagingException { try { InputStream xis = part.getInputStream(); // transfer decoded only // now construct a reader from the decoded stream return MessageUtilities.getTextReader(xis, charset); } catch (IOException xex) { throw new MessagingException(xex.toString()); } }
From source file:com.stimulus.archiva.extraction.MessageExtraction.java
private void writeAttachment(Part p, String filename) { filename = getFilename(filename, "attachment.att"); File attachFile = new File(Config.getFileSystem().getViewPath() + File.separatorChar + filename); OutputStream os = null;/* w ww .jav a 2s. co m*/ InputStream is = null; try { logger.debug("writing attachment {filename='" + attachFile.getAbsolutePath() + "'}"); os = new BufferedOutputStream(new FileOutputStream(attachFile)); is = p.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); int c = 0; while ((c = bis.read()) != -1) { os.write(c); } os.close(); bis.close(); Config.getFileSystem().getTempFiles().markForDeletion(attachFile); } catch (Exception ex) { logger.error("failed to write attachment {filename='" + attachFile + "'}", ex); } finally { try { if (os != null) os.close(); if (is != null) is.close(); } catch (Exception e) { } } }
From source file:org.xmlactions.email.EMailParser.java
private void addPart(Part part) throws IOException, MessagingException, DocumentException { String contentType = part.getContentType(); boolean isAttachment; if (part.getFileName() != null) { isAttachment = true;/* w w w .j av a 2 s. co m*/ } else { isAttachment = false; } log.debug("isAttachment:" + isAttachment + " contentType:" + contentType); if (isAttachment == true) { } else { // Check if plain if (contentType.toLowerCase().indexOf("text/plain") >= 0) { log.debug("process text/plain"); setIgnoreHTML(true); // if we get any text/plain for body } else if (isIgnoreHTML() == false && contentType.toLowerCase().indexOf("text/html") >= 0) { // log.debug("skipping text/html"); log.debug("process text/html"); InputStream is = convertHTMLToText(part.getInputStream()); try { } finally { IOUtils.closeQuietly(is); } } else { log.debug("ignoring part [" + contentType + "]"); } } }
From source file:org.apache.james.transport.mailets.StripAttachment.java
/** * Saves the content of the part to a file in the given directoy, using the * name of the part. If a file with that name already exists, it will * //from w ww.jav a 2 s . co m * @param part * The MIME part to save. * @return * @throws Exception */ private String saveAttachmentToFile(Part part, String fileName) throws Exception { BufferedOutputStream os = null; InputStream is = null; File f = null; try { if (fileName == null) fileName = part.getFileName(); int pos = -1; if (fileName != null) { pos = fileName.lastIndexOf("."); } String prefix = pos > 0 ? (fileName.substring(0, pos)) : fileName; String suffix = pos > 0 ? (fileName.substring(pos)) : ".bin"; while (prefix.length() < 3) prefix += "_"; if (suffix.length() == 0) suffix = ".bin"; f = File.createTempFile(prefix, suffix, new File(directoryName)); log("saving content of " + f.getName() + "..."); os = new BufferedOutputStream(new FileOutputStream(f)); is = part.getInputStream(); if (!(is instanceof BufferedInputStream)) { is = new BufferedInputStream(is); } int c; while ((c = is.read()) != -1) { os.write(c); } return f.getName(); } catch (Exception e) { log("Error while saving contents of [" + (f != null ? f.getName() : (part != null ? part.getFileName() : "NULL")) + "].", e); throw e; } finally { is.close(); os.close(); } }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * Decode contents of TEXT/PLAIN message parts into UTF encoded strings. * Why can't JAVA Mail provide this method?? Who knows!?!?!? * * @param buffer DOCUMENT ME!/* w w w .j a va2 s .c o m*/ * @param part DOCUMENT ME! * * @return DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static StringBuffer decodeTextPlain(StringBuffer buffer, Part part, String breakLine, String charset) throws MessagingException { // pick off the individual lines of text // and append to the buffer try { StringBuffer buff = new StringBuffer(); BufferedReader xreader = MessageUtilities.getTextReader(part.getInputStream(), charset); for (String xline; (xline = xreader.readLine()) != null;) { buff.append(xline); buff.append(breakLine); } xreader.close(); //String aux = JavaScriptFilter.apply(buff.toString()); buffer.append(buff.toString()); return buffer; } catch (IOException xex) { throw new MessagingException(xex.toString()); } }
From source file:org.nuxeo.ecm.platform.mail.listener.action.ExtractMessageInformationAction.java
protected void getAttachmentParts(Part part, String defaultFilename, MimetypeRegistry mimeService, ExecutionContext context) throws MessagingException, IOException { String filename = getFilename(part, defaultFilename); List<Blob> blobs = (List<Blob>) context.get(ATTACHMENTS_KEY); if (part.isMimeType("multipart/alternative")) { bodyContent += getText(part);/*from ww w . j a va 2 s .co m*/ } else { if (!part.isMimeType("multipart/*")) { String disp = part.getDisposition(); // no disposition => mail body, which can be also blob (image for // instance) if (disp == null && // convert only text part.getContentType().toLowerCase().startsWith("text/")) { bodyContent += decodeMailBody(part); } else { Blob blob; try (InputStream in = part.getInputStream()) { blob = Blobs.createBlob(in); } String mime = DEFAULT_BINARY_MIMETYPE; try { if (mimeService != null) { ContentType contentType = new ContentType(part.getContentType()); mime = mimeService.getMimetypeFromFilenameAndBlobWithDefault(filename, blob, contentType.getBaseType()); } } catch (MessagingException | MimetypeDetectionException e) { log.error(e); } blob.setMimeType(mime); blob.setFilename(filename); blobs.add(blob); } } if (part.isMimeType("multipart/*")) { // This is a Multipart Multipart mp = (Multipart) part.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) { getAttachmentParts(mp.getBodyPart(i), defaultFilename, mimeService, context); } } else if (part.isMimeType(MESSAGE_RFC822_MIMETYPE)) { // This is a Nested Message getAttachmentParts((Part) part.getContent(), defaultFilename, mimeService, context); } } }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Writes a passed payload part to the passed message object. *//*from w w w .j a va 2 s . c o m*/ public void writePayloadsToMessage(Part payloadPart, AS2Message message, Properties header) throws Exception { List<Part> attachmentList = new ArrayList<Part>(); AS2Info info = message.getAS2Info(); if (!info.isMDN()) { AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info(); if (payloadPart.isMimeType("multipart/*")) { //check if it is a CEM if (payloadPart.getContentType().toLowerCase().contains("application/ediint-cert-exchange+xml")) { messageInfo.setMessageType(AS2Message.MESSAGETYPE_CEM); if (this.logger != null) { this.logger.log(Level.FINE, this.rb.getResourceString("found.cem", new Object[] { messageInfo.getMessageId(), message }), info); } } ByteArrayOutputStream mem = new ByteArrayOutputStream(); payloadPart.writeTo(mem); mem.flush(); mem.close(); MimeMultipart multipart = new MimeMultipart( new ByteArrayDataSource(mem.toByteArray(), payloadPart.getContentType())); //add all attachments to the message for (int i = 0; i < multipart.getCount(); i++) { //its possible that one of the bodyparts is the signature (for compressed/signed messages), skip the signature if (!multipart.getBodyPart(i).getContentType().toLowerCase().contains("pkcs7-signature")) { attachmentList.add(multipart.getBodyPart(i)); } } } else { attachmentList.add(payloadPart); } } else { //its a MDN, write whole part attachmentList.add(payloadPart); } //write the parts for (Part attachmentPart : attachmentList) { ByteArrayOutputStream payloadOut = new ByteArrayOutputStream(); InputStream payloadIn = attachmentPart.getInputStream(); this.copyStreams(payloadIn, payloadOut); payloadOut.flush(); payloadOut.close(); byte[] data = payloadOut.toByteArray(); AS2Payload as2Payload = new AS2Payload(); as2Payload.setData(data); String[] contentIdHeader = attachmentPart.getHeader("content-id"); if (contentIdHeader != null && contentIdHeader.length > 0) { as2Payload.setContentId(contentIdHeader[0]); } String[] contentTypeHeader = attachmentPart.getHeader("content-type"); if (contentTypeHeader != null && contentTypeHeader.length > 0) { as2Payload.setContentType(contentTypeHeader[0]); } try { as2Payload.setOriginalFilename(payloadPart.getFileName()); } catch (MessagingException e) { if (this.logger != null) { this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error", new Object[] { info.getMessageId(), e.getMessage(), }), info); } } if (as2Payload.getOriginalFilename() == null) { String filenameheader = header.getProperty("content-disposition"); if (filenameheader != null) { //test part for convinience: extract file name MimeBodyPart filenamePart = new MimeBodyPart(); filenamePart.setHeader("content-disposition", filenameheader); try { as2Payload.setOriginalFilename(filenamePart.getFileName()); } catch (MessagingException e) { if (this.logger != null) { this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error", new Object[] { info.getMessageId(), e.getMessage(), }), info); } } } } message.addPayload(as2Payload); } }
From source file:org.klco.email2html.OutputWriter.java
/** * Writes the attachment contained in the body part to a file. * /*from w ww . j ava 2 s. c o m*/ * @param containingMessage * the message this body part is contained within * @param part * the part containing the attachment * @return the file that was created/written to * @throws IOException * Signals that an I/O exception has occurred. * @throws MessagingException * the messaging exception */ public boolean writeAttachment(EmailMessage containingMessage, Part part) throws IOException, MessagingException { log.trace("writeAttachment"); File attachmentFolder; File attachmentFile; InputStream in = null; OutputStream out = null; try { attachmentFolder = new File(outputDir.getAbsolutePath() + File.separator + config.getImagesSubDir() + File.separator + FILE_DATE_FORMAT.format(containingMessage.getSentDate())); if (!attachmentFolder.exists()) { log.debug("Creating attachment folder"); attachmentFolder.mkdirs(); } attachmentFile = new File(attachmentFolder, part.getFileName()); log.debug("Writing attachment file: {}", attachmentFile.getAbsolutePath()); if (!attachmentFile.exists()) { attachmentFile.createNewFile(); } in = new BufferedInputStream(part.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(attachmentFile)); log.debug("Downloading attachment"); CRC32 checksum = new CRC32(); for (int b = in.read(); b != -1; b = in.read()) { checksum.update(b); out.write(b); } if (this.excludeDuplicates) { log.debug("Computing checksum"); long value = checksum.getValue(); if (this.attachmentChecksums.contains(value)) { log.info("Skipping duplicate attachment: {}", part.getFileName()); attachmentFile.delete(); return false; } else { attachmentChecksums.add(value); } } log.debug("Attachement saved"); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } if (part.getContentType().toLowerCase().startsWith("image")) { log.debug("Creating renditions"); String contentType = part.getContentType().substring(0, part.getContentType().indexOf(";")); log.debug("Creating renditions of type: " + contentType); for (Rendition rendition : renditions) { File renditionFile = new File(attachmentFolder, rendition.getName() + "-" + part.getFileName()); try { if (!renditionFile.exists()) { renditionFile.createNewFile(); } log.debug("Creating rendition file: {}", renditionFile.getAbsolutePath()); createRendition(attachmentFile, renditionFile, rendition); log.debug("Rendition created"); } catch (OutOfMemoryError oome) { Runtime rt = Runtime.getRuntime(); rt.gc(); log.warn("Ran out of memory creating rendition: " + rendition, oome); log.warn("Free Memory: {}", rt.freeMemory()); log.warn("Max Memory: {}", rt.maxMemory()); log.warn("Total Memory: {}", rt.totalMemory()); String[] command = null; if (rendition.getFill()) { command = new String[] { "convert", attachmentFile.getAbsolutePath(), "-resize", (rendition.getHeight() * 2) + "x", "-resize", "'x" + (rendition.getHeight() * 2) + "<'", "-resize", "50%", "-gravity", "center", "-crop", rendition.getHeight() + "x" + rendition.getWidth() + "+0+0", "+repage", renditionFile.getAbsolutePath() }; } else { command = new String[] { "convert", attachmentFile.getAbsolutePath(), "-resize", rendition.getHeight() + "x" + rendition.getWidth(), renditionFile.getAbsolutePath() }; } log.debug("Trying to resize with ImageMagick: " + StringUtils.join(command, " ")); rt.exec(command); } catch (Exception t) { log.warn("Exception creating rendition: " + rendition, t); } } } return true; }
From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * @param part/* w w w. ja v a 2 s. c o m*/ * @param attach * @return * @throws Exception */ private FileUtil handlePart(Part part, boolean attach) throws Exception { FileUtil file = null; String disposition = part.getDisposition(); if (disposition == null) { // no nothing } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE)) { file = new FileUtil(); String fileName = part.getFileName(); String contentType = part.getContentType(); /* * The contentType parameter contains mimetype and filename in one */ String mimeType = contentType.split(";")[0].trim(); file.setFilename(fileName); file.setMimetype(mimeType); InputStream inputStream = (attach == true) ? part.getInputStream() : null; if (inputStream != null) file.setInputStream(inputStream, mimeType); } return file; }