List of usage examples for javax.mail Part getContentType
public String getContentType() throws MessagingException;
From source file:org.alfresco.module.org_alfresco_module_rm.action.impl.SplitEmailAction.java
/** * Create attachment from Mime Message Part * @param messageNodeRef - the node ref of the mime message * @param parentNodeRef - the node ref of the parent folder * @param part// w w w. j a v a 2 s. co m * @throws MessagingException * @throws IOException */ private void createAttachment(NodeRef messageNodeRef, NodeRef parentNodeRef, Part part) throws MessagingException, IOException { String fileName = part.getFileName(); try { fileName = MimeUtility.decodeText(fileName); } catch (UnsupportedEncodingException e) { if (logger.isWarnEnabled()) { logger.warn("Cannot decode file name '" + fileName + "'", e); } } Map<QName, Serializable> messageProperties = getNodeService().getProperties(messageNodeRef); String messageTitle = (String) messageProperties.get(ContentModel.PROP_NAME); if (messageTitle == null) { messageTitle = fileName; } else { messageTitle = messageTitle + " - " + fileName; } ContentType contentType = new ContentType(part.getContentType()); Map<QName, Serializable> docProps = new HashMap<QName, Serializable>(1); docProps.put(ContentModel.PROP_NAME, messageTitle + " - " + fileName); docProps.put(ContentModel.PROP_TITLE, fileName); /** * Create an attachment node in the same folder as the message */ ChildAssociationRef attachmentRef = getNodeService().createNode(parentNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, fileName), ContentModel.TYPE_CONTENT, docProps); /** * Write the content into the new attachment node */ ContentWriter writer = getContentService().getWriter(attachmentRef.getChildRef(), ContentModel.PROP_CONTENT, true); writer.setMimetype(contentType.getBaseType()); OutputStream os = writer.getContentOutputStream(); FileCopyUtils.copy(part.getInputStream(), os); /** * Create a link from the message to the attachment */ createRMReference(messageNodeRef, attachmentRef.getChildRef()); }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * A 'safe' version of JavaMail getContentType(), i.e. don't throw * exceptions. The part is interogated for a valid content type. If the * content type is missing or invalid, a default content type of * "text/plain" is assumed, which is suggested by the MIME standard. * * @param part The part to interogate//ww w .ja v a 2s .c om * * @return ContentType of the part * * @see javax.mail.Part */ public static ContentType getContentType(Part part) { String xtype = null; try { xtype = part.getContentType(); } catch (MessagingException xex) { } if (xtype == null) { xtype = "text/plain"; // MIME default content type if missing } ContentType xctype = null; try { xctype = new ContentType(xtype.toLowerCase()); } catch (ParseException xex) { } if (xctype == null) { xctype = new ContentType("text", "plain", null); } return xctype; }
From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * @param part/* www . j a v a2 s. c om*/ * @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; }
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 . c om } 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:mitm.common.pdf.MessagePDFBuilder.java
private void addAttachment(final Part part, PdfWriter pdfWriter) throws IOException, MessagingException { byte[] content = IOUtils.toByteArray(part.getInputStream()); String filename = StringUtils .defaultString(HeaderUtils.decodeTextQuietly(MimeUtils.getFilenameQuietly(part)), "attachment.bin"); String baseType;//from www. ja v a 2s. c o m String contentType = null; try { contentType = part.getContentType(); MimeType mimeType = new MimeType(contentType); baseType = mimeType.getBaseType(); } catch (MimeTypeParseException e) { /* * Can happen when the content-type is not correct. Example with missing ; between charset and name: * * Content-Type: application/pdf; * charset="Windows-1252" name="postcard2010.pdf" */ logger.warn("Unable to infer MimeType from content type. Fallback to application/octet-stream. " + "Content-Type: " + contentType); baseType = MimeTypes.OCTET_STREAM; } PdfFileSpecification fileSpec = PdfFileSpecification.fileEmbedded(pdfWriter, null, filename, content, true /* compress */, baseType, null); pdfWriter.addFileAttachment(fileSpec); }
From source file:org.klco.email2html.OutputWriter.java
/** * Adds the attachment to the EmailMessage. Call this method when the email * content has most likely already been loaded. * //from www . j av a2 s .c o m * @param containingMessage * the Email Message to add the attachment to * @param part * the content of the attachment * @throws IOException * @throws MessagingException */ public void addAttachment(EmailMessage containingMessage, Part part) throws IOException, MessagingException { log.trace("addAttachment"); File attachmentFolder = new File(outputDir.getAbsolutePath() + File.separator + config.getImagesSubDir() + File.separator + FILE_DATE_FORMAT.format(containingMessage.getSentDate())); File attachmentFile = new File(attachmentFolder, part.getFileName()); boolean addAttachment = true; boolean writeAttachment = false; if (!attachmentFolder.exists() || !attachmentFile.exists()) { log.warn("Attachment or folder missing, writing attachment {}", attachmentFile.getName()); writeAttachment = true; } if (!writeAttachment && part.getContentType().toLowerCase().startsWith("image")) { for (Rendition rendition : renditions) { File renditionFile = new File(attachmentFolder, rendition.getName() + "-" + part.getFileName()); if (!renditionFile.exists()) { log.warn("Rendition {} missing, writing attachment {}", renditionFile.getName(), attachmentFile.getName()); writeAttachment = true; break; } } } if (writeAttachment) { addAttachment = writeAttachment(containingMessage, part); } else { if (this.excludeDuplicates) { log.debug("Computing checksum"); InputStream is = null; try { CRC32 checksum = new CRC32(); is = new BufferedInputStream(new FileInputStream(attachmentFile)); for (int read = is.read(); read != -1; read = is.read()) { checksum.update(read); } long value = checksum.getValue(); if (attachmentChecksums.contains(value)) { addAttachment = false; } else { attachmentChecksums.add(checksum.getValue()); } } finally { IOUtils.closeQuietly(is); } } } if (addAttachment) { containingMessage.getAttachments().add(attachmentFile); } else { log.debug("Attachment is a duplicate, not adding as message attachment"); } }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Returns a compressed part of this container if it exists, else null. If the container itself *is compressed it is returned.//from w ww.j av a 2s . c om */ public Part getCompressedEmbeddedPart(Part part) throws MessagingException, IOException { if (this.contentTypeIndicatesCompression(part.getContentType())) { return (part); } if (part.isMimeType("multipart/*")) { Multipart multiPart = (Multipart) part.getContent(); int count = multiPart.getCount(); for (int i = 0; i < count; i++) { BodyPart bodyPart = multiPart.getBodyPart(i); Part compressedEmbeddedPart = this.getCompressedEmbeddedPart(bodyPart); if (compressedEmbeddedPart != null) { return (compressedEmbeddedPart); } } } return (null); }
From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java
/** * Handle a part of a email message. This is either displayable text or some MIME * attachment./*from w ww . ja v a 2 s . c o m*/ * * @param part The part to handle. * @throws MessagingException * @throws IOException */ private void handlePart(Part part) throws MessagingException, IOException { /* get the content type of this part */ String contentType = part.getContentType(); if (part.getContent() instanceof Multipart) { handleMultipart((Multipart) part.getContent()); return; } log.info("Content-Type: " + contentType); /* check if the content is printable */ if (contentType.toLowerCase().startsWith("text/plain") && blogEntryContent == null) { /* get the charset */ Charset charset = getCharsetFromHeader(contentType); /* set the blog entry content to this content */ blogEntryContent = ""; InputStream is = part.getInputStream(); BufferedReader br = null; if (charset != null) { br = new BufferedReader(new InputStreamReader(is, charset)); } else { br = new BufferedReader(new InputStreamReader(is)); } String currentLine = null; while ((currentLine = br.readLine()) != null) { blogEntryContent = blogEntryContent.concat(currentLine).concat("\r\n"); } } else { /* the content is not text, so we assume it is some sort of MIME attachment */ try { /* get the filename */ String fileName = part.getFileName(); /* no filename, ignore this part */ if (fileName == null) { this.log.warn("Attachment with no filename. Ignoring."); return; } /* retrieve an input stream to the attachment */ InputStream is = part.getInputStream(); /* clean-up the content type (only the part before the first ';' is relevant) */ if (contentType.indexOf(';') != -1) { contentType = contentType.substring(0, contentType.indexOf(';')); } if (contentType.toLowerCase().indexOf("image") != -1) { /* this post contains an image as attachment, add the gallery macro to the blog post */ containsImage = true; } ByteArrayInputStream bais = null; byte[] attachment = null; /* put the attachment into a byte array */ try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int numBytes; while (true) { numBytes = is.read(buf); if (numBytes > 0) { baos.write(buf, 0, numBytes); } else { /* end of stream reached */ break; } } /* create a new input stream */ attachment = baos.toByteArray(); bais = new ByteArrayInputStream(attachment); //this.log.info("Attachment size: " + attachment.length); } catch (Exception e) { this.log.error("Could not load attachment:" + e.getMessage(), e); /* skip this attachment */ throw e; } /* create a new attachment */ Attachment a = new Attachment(fileName, contentType, attachment.length, "Attachment added by mail2news"); Date d = new Date(); a.setCreationDate(d); a.setLastModificationDate(d); /* add the attachment and the input stream to the attachment to the list * of attachments of the current blog entry */ attachments.addLast(a); attachmentsInputStreams.addLast(bais); } catch (Exception e) { this.log.error("Error while saving attachment: " + e.getMessage(), e); } } }
From source file:org.silverpeas.core.mail.extractor.EMLExtractor.java
private String processMailPart(Part part, List<MailAttachment> attachments) throws MessagingException, IOException { if (!isTextPart(part)) { Object content = part.getContent(); if (content instanceof Multipart) { Multipart mContent = (Multipart) content; return processMultipart(mContent, attachments); } else if (attachments != null) { String fileName = getFileName(part); if (fileName != null) { MailAttachment attachment = new MailAttachment(fileName); String dir = FileRepositoryManager.getTemporaryPath() + "mail" + System.currentTimeMillis(); File file = new File(dir, fileName); FileUtils.copyInputStreamToFile(part.getInputStream(), file); attachment.setPath(file.getAbsolutePath()); attachment.setSize(file.length()); attachments.add(attachment); }// ww w. j av a2 s . c o m } } else { if (part.getContentType().indexOf(MimeTypes.HTML_MIME_TYPE) >= 0) { return (String) part.getContent(); } else if (part.getContentType().indexOf(MimeTypes.PLAIN_TEXT_MIME_TYPE) >= 0) { return WebEncodeHelper.javaStringToHtmlParagraphe((String) part.getContent()); } } return ""; }
From source file:org.silverpeas.util.mail.EMLExtractor.java
private String processMailPart(Part part, List<MailAttachment> attachments) throws MessagingException, IOException { if (!isTextPart(part)) { Object content = part.getContent(); if (content instanceof Multipart) { Multipart mContent = (Multipart) content; return processMultipart(mContent, attachments); } else if (attachments != null) { String fileName = getFileName(part); if (fileName != null) { MailAttachment attachment = new MailAttachment(fileName); String dir = FileRepositoryManager.getTemporaryPath() + "mail" + System.currentTimeMillis(); File file = new File(dir, fileName); FileUtils.copyInputStreamToFile(part.getInputStream(), file); attachment.setPath(file.getAbsolutePath()); attachment.setSize(file.length()); attachments.add(attachment); }//from w w w.j av a 2 s. c o m } } else { if (part.getContentType().indexOf(MimeTypes.HTML_MIME_TYPE) >= 0) { return (String) part.getContent(); } else if (part.getContentType().indexOf(MimeTypes.PLAIN_TEXT_MIME_TYPE) >= 0) { return EncodeHelper.javaStringToHtmlParagraphe((String) part.getContent()); } } return ""; }