List of usage examples for javax.mail Part isMimeType
public boolean isMimeType(String mimeType) throws MessagingException;
From source file:org.alfresco.repo.content.transform.EmailToPDFContentTransformer.java
/** * Do txt transform of eml file./*from www . j a v a2 s.com*/ * * @param is * the input stream * @param os * the final output stream * @param inputMime * the input mime type * @param targetMimeType * the target mime type * @param encoding * the encoding of reader * @param writerEncoding * the writer encoding * @throws IOException * Signals that an I/O exception has occurred. * @throws TransformerConfigurationException * the transformer configuration exception * @throws SAXException * the sAX exception * @throws TikaException * the tika exception * @throws MessagingException * the messaging exception */ protected void doTxtTransform(InputStream is, OutputStream os, String inputMime, String targetMimeType, String encoding, String writerEncoding) throws IOException, TransformerConfigurationException, SAXException, TikaException, MessagingException { MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()), is); final StringBuilder sb = new StringBuilder(); Object content = mimeMessage.getContent(); if (content instanceof Multipart) { Multipart multipart = (Multipart) content; Part part = multipart.getBodyPart(0); if (part.getContent() instanceof Multipart) { multipart = (Multipart) part.getContent(); for (int i = 0, n = multipart.getCount(); i < n; i++) { part = multipart.getBodyPart(i); if (part.isMimeType("text/*")) { sb.append(part.getContent().toString()).append("\n"); } } } else if (part.isMimeType("text/*")) { sb.append(part.getContent().toString()); } } else { sb.append(content.toString()); } textToPDF(new ByteArrayInputStream(sb.toString().getBytes()), UTF_8, os); }
From source file:org.alfresco.repo.content.transform.EMLParser.java
/** * Adapted extract multipart is the recusrsive parser that splits the data and apend it to the * final xhtml file.//w ww . j a v a2s . c om * * @param xhtml * the xhtml * @param part * the part * @param parentPart * the parent part * @param context * the context * @throws MessagingException * the messaging exception * @throws IOException * Signals that an I/O exception has occurred. * @throws SAXException * the sAX exception * @throws TikaException * the tika exception */ public void adaptedExtractMultipart(XHTMLContentHandler xhtml, Part part, Part parentPart, ParseContext context) throws MessagingException, IOException, SAXException, TikaException { String disposition = part.getDisposition(); if ((disposition != null && disposition.contains(Part.ATTACHMENT))) { return; } if (part.isMimeType("text/plain")) { if (parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE)) { return; } else { // add file String data = part.getContent().toString(); writeContent(part, data, MimetypeMap.MIMETYPE_TEXT_PLAIN, "txt"); } } else if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); Part parentPartLocal = part; if (parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE)) { parentPartLocal = parentPart; } int count = mp.getCount(); for (int i = 0; i < count; i++) { adaptedExtractMultipart(xhtml, mp.getBodyPart(i), parentPartLocal, context); } } else if (part.isMimeType("message/rfc822")) { adaptedExtractMultipart(xhtml, (Part) part.getContent(), part, context); } else if (part.isMimeType("text/html")) { if ((parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE)) || (part.getDisposition() == null || !part.getDisposition().contains(Part.ATTACHMENT))) { Object data = part.getContent(); String htmlFileData = prepareString(new String(data.toString())); writeContent(part, htmlFileData, MimetypeMap.MIMETYPE_HTML, "html"); } } else if (part.isMimeType("image/*")) { String[] encoded = part.getHeader("Content-Transfer-Encoding"); if (isContained(encoded, "base64")) { if (part.getDisposition() != null && part.getDisposition().contains(Part.ATTACHMENT)) { InputStream stream = part.getInputStream(); byte[] binaryData = new byte[part.getSize()]; stream.read(binaryData, 0, part.getSize()); String encodedData = new String(Base64.encodeBase64(binaryData)); String[] split = part.getContentType().split(";"); String src = "data:" + split[0].trim() + ";base64," + encodedData; AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute(null, "src", "src", "String", src); xhtml.startElement("img", attributes); xhtml.endElement("img"); } } } else { Object content = part.getContent(); if (content instanceof String) { xhtml.element("div", prepareString(part.getContent().toString())); } else if (content instanceof InputStream) { InputStream fileContent = part.getInputStream(); Parser parser = new AutoDetectParser(); Metadata attachmentMetadata = new Metadata(); BodyContentHandler handlerAttachments = new BodyContentHandler(); parser.parse(fileContent, handlerAttachments, attachmentMetadata, context); xhtml.element("div", handlerAttachments.toString()); } } }
From source file:com.stimulus.archiva.domain.Email.java
protected boolean hasAttachment(Part p) throws MessagingException, IOException { if (p.getDisposition() != null && Compare.equalsIgnoreCase(p.getDisposition(), Part.ATTACHMENT)) { logger.debug("hasAttachment() attachment disposition."); return true; }//from ww w . j a v a2 s . c o m if (p.getFileName() != null) { logger.debug("hasAttachment() filename specified."); return true; } try { if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); for (int i = 0; i < mp.getCount(); i++) { logger.debug("hasAttachment() scanning multipart[" + i + "]"); if (hasAttachment(mp.getBodyPart(i))) return true; } } else if (p.isMimeType("message/rfc822")) { return hasAttachment((Part) p.getContent()); } } catch (Exception e) { logger.debug("exception occurred while detecting attachment", e); } return false; }
From source file:mitm.application.djigzo.james.mailets.BlackberrySMIMEAdapter.java
private Part findAttachment(MimeMessage containerMessage) throws MessagingException, IOException, PartException { final MutableObject smimePart = new MutableObject(); final MutableObject octetPart = new MutableObject(); PartListener partListener = new PartScanner.PartListener() { @Override/*from w w w . j ava2 s .c o m*/ public boolean onPart(Part parent, Part part, Object context) throws PartException { try { if (ArrayUtils.contains(part.getHeader(DjigzoHeader.MARKER), DjigzoHeader.ATTACHMENT_MARKER_VALUE)) { smimePart.setValue(part); /* * we found the part with the marker so we can stop scanning */ return false; } /* * Fallback scanning for octet-stream in case the template does not contain a DjigzoHeader.MARKER */ if (part.isMimeType("application/octet-stream")) { octetPart.setValue(part); } return true; } catch (MessagingException e) { throw new PartException(e); } } }; PartScanner partScanner = new PartScanner(partListener, MAX_DEPTH); partScanner.scanPart(containerMessage); Part result = (Part) smimePart.getValue(); if (result == null) { result = (Part) octetPart.getValue(); if (result != null) { logger.debug("Marker not found. Using octet-stream instead."); } else { throw new MessagingException("Unable to find the attachment part in the template."); } } return result; }
From source file:org.jahia.modules.gateway.mail.MailToJSONImpl.java
protected void parseMailMessage(Part part, MailContent content) throws IOException, MessagingException { Object mailContent = part.getContent(); if (mailContent instanceof MimeMultipart) { MimeMultipart mailMessageContent = (MimeMultipart) mailContent; // We have some attachments for (int i = 0; i < mailMessageContent.getCount(); i++) { BodyPart bodyPart = mailMessageContent.getBodyPart(i); parseMailMessage(bodyPart, content); }/*from ww w . j a v a 2 s . c om*/ } else if (mailContent instanceof String && part.getDisposition() == null) { boolean isHtml = false; if (content.getBody() == null || ((isHtml = part.isMimeType("text/html")) && !content.isHtml())) { if (isHtml) { content.setBodyHtml((String) mailContent); } else { content.setBody((String) mailContent); } } } else if (mailContent instanceof InputStream || mailContent instanceof String) { File tempFile = File.createTempFile("mail2json-", null); try { FileUtils.copyInputStreamToFile( mailContent instanceof InputStream ? (InputStream) mailContent : part.getInputStream(), tempFile); content.getFiles() .add(new FileItem(StringUtils.defaultIfEmpty(part.getFileName(), "unknown"), tempFile)); } catch (IOException e) { FileUtils.deleteQuietly(tempFile); throw e; } } assert content.getBody() != null; }
From source file:org.apache.solr.handler.dataimport.FsMailEntityProcessor.java
public boolean addPartToDocument(Part part, Map<String, Object> row, boolean outerMost) throws Exception { if (outerMost && part instanceof Message) { if (!addEnvelopToDocument(part, row)) { return false; }/* w w w . j av a2 s . c o m*/ // store hash row.put(HASH, DigestUtils.md5Hex((String) row.get(FROM_CLEAN) + "" + (String) row.get(SUBJECT))); } String ct = part.getContentType(); ContentType ctype = new ContentType(ct); if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); int count = mp.getCount(); if (part.isMimeType("multipart/alternative")) { count = 1; } for (int i = 0; i < count; i++) { addPartToDocument(mp.getBodyPart(i), row, false); } } else if (part.isMimeType("message/rfc822")) { addPartToDocument((Part) part.getContent(), row, false); } else { String disp = part.getDisposition(); @SuppressWarnings("resource") // Tika will close stream InputStream is = part.getInputStream(); String fileName = part.getFileName(); Metadata md = new Metadata(); md.set(HttpHeaders.CONTENT_TYPE, ctype.getBaseType().toLowerCase(Locale.ROOT)); md.set(TikaMetadataKeys.RESOURCE_NAME_KEY, fileName); String content = this.tika.parseToString(is, md); if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) { if (row.get(ATTACHMENT) == null) { row.put(ATTACHMENT, new ArrayList<String>()); } List<String> contents = (List<String>) row.get(ATTACHMENT); contents.add(content); row.put(ATTACHMENT, contents); if (row.get(ATTACHMENT_NAMES) == null) { row.put(ATTACHMENT_NAMES, new ArrayList<String>()); } List<String> names = (List<String>) row.get(ATTACHMENT_NAMES); names.add(fileName); row.put(ATTACHMENT_NAMES, names); } else { if (row.get(CONTENT) == null) { row.put(CONTENT, new ArrayList<String>()); } List<String> contents = (List<String>) row.get(CONTENT); contents.add(content); row.put(CONTENT, contents); } } return true; }
From source file:com.szmslab.quickjavamail.receive.MessageLoader.java
/** * ?????MessageContent????/*from w w w . j a v a 2s . co m*/ * * @param multiPart * ? * @param msgContent * ???? * @throws MessagingException * @throws IOException */ private void setMultipartContent(Multipart multiPart, MessageContent msgContent) throws MessagingException, IOException { for (int i = 0; i < multiPart.getCount(); i++) { Part part = multiPart.getBodyPart(i); if (part.getContentType().indexOf("multipart") >= 0) { setMultipartContent((Multipart) part.getContent(), msgContent); } else { String disposition = part.getDisposition(); if (Part.ATTACHMENT.equals(disposition)) { // Disposition?"attachment"???ContentType???? msgContent.attachmentFileList.add(new AttachmentFile(MimeUtility.decodeText(part.getFileName()), part.getDataHandler().getDataSource())); } else { if (part.isMimeType("text/html")) { msgContent.html = part.getContent().toString(); } else if (part.isMimeType("text/plain")) { msgContent.text = part.getContent().toString(); } else { // Disposition?"inline"???ContentType?? if (Part.INLINE.equals(disposition)) { String cid = ""; if (part instanceof MimeBodyPart) { MimeBodyPart mimePart = (MimeBodyPart) part; cid = mimePart.getContentID(); } msgContent.inlineImageFileList .add(new InlineImageFile(cid, MimeUtility.decodeText(part.getFileName()), part.getDataHandler().getDataSource())); } } } } } }
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 w w. jav a2 s .c o m */ 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:org.alfresco.repo.content.transform.EMLParser.java
/** * Prepare extract multipart.// w ww .j a v a 2 s . c om * * @param xhtml * the xhtml * @param part * the part * @param parentPart * the parent part * @param context * the context * @param attachmentList * is list with attachments to fill * @throws MessagingException * the messaging exception * @throws IOException * Signals that an I/O exception has occurred. * @throws SAXException * the sAX exception * @throws TikaException * the tika exception */ private void prepareExtractMultipart(XHTMLContentHandler xhtml, Part part, Part parentPart, ParseContext context, List<String> attachmentList) throws MessagingException, IOException, SAXException, TikaException { String disposition = part.getDisposition(); if ((disposition != null && disposition.contains(Part.ATTACHMENT))) { String fileName = part.getFileName(); if (fileName != null && fileName.startsWith("=?")) { fileName = MimeUtility.decodeText(fileName); } attachmentList.add(fileName); } String[] header = part.getHeader("Content-ID"); String key = null; if (header != null) { for (String string : header) { key = string; } } if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) { prepareExtractMultipart(xhtml, mp.getBodyPart(i), part, context, attachmentList); } } else if (part.isMimeType(MimetypeMap.MIMETYPE_RFC822)) { prepareExtractMultipart(xhtml, (Part) part.getContent(), part, context, attachmentList); } else { if (key == null) { return; } // if ((disposition != null && disposition.contains(Part.INLINE))) { InputStream stream = part.getInputStream(); File file = new File(workingDirectory, System.currentTimeMillis() + ""); FileOutputStream fileOutputStream = new FileOutputStream(file); IOUtils.copy(stream, fileOutputStream); IOUtils.closeQuietly(fileOutputStream); String src = file.getName(); String replace = key.replace("<", "").replace(">", ""); referencesCache.put(replace, src); // } } }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Writes a passed payload part to the passed message object. *///from w ww . j a v a 2 s. c om 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); } }