List of usage examples for javax.mail Part getContent
public Object getContent() throws IOException, MessagingException;
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 . jav 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: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 . j a v a2 s. 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:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Verifies the signature of the passed signed part*/ public MimeBodyPart verifySignedPart(Part signedPart, byte[] data, String contentType, X509Certificate certificate) throws Exception { BCCryptoHelper helper = new BCCryptoHelper(); String signatureTransferEncoding = null; MimeMultipart checkPart = (MimeMultipart) signedPart.getContent(); //it is sure that it is a signed part: set the type to multipart if the //parser has problems parsing it. Don't know why sometimes a parsing fails for //MimeBodyPart. This check looks if the parser is able to find more than one subpart if (checkPart.getCount() == 1) { MimeMultipart multipart = new MimeMultipart(new ByteArrayDataSource(data, contentType)); MimeMessage possibleSignedMessage = new MimeMessage(Session.getInstance(System.getProperties(), null)); possibleSignedMessage.setContent(multipart, multipart.getContentType()); possibleSignedMessage.saveChanges(); //overwrite the formerly found signed part signedPart = helper.getSignedEmbeddedPart(possibleSignedMessage); }//from w w w . j a va 2s .c om //get the content encoding of the signature MimeMultipart signedMultiPart = (MimeMultipart) signedPart.getContent(); //body part 1 is always the signature String encodingHeader[] = signedMultiPart.getBodyPart(1).getHeader("Content-Transfer-Encoding"); if (encodingHeader != null) { signatureTransferEncoding = encodingHeader[0]; } return (helper.verify(signedPart, signatureTransferEncoding, certificate)); }
From source file:org.alfresco.repo.content.transform.EMLParser.java
/** * Prepare extract multipart./*from w w w. j av a2s .co m*/ * * @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:org.zilverline.core.IMAPCollection.java
/** * Index a part./*from w w w .j a v a2 s.com*/ */ private void indexPart(final Document doc, final Part p) throws MessagingException, IOException { int size = p.getSize(); String ct = p.getContentType(); String cd = p.getDescription(); log.debug("IndexContent, type: " + ct + ", description: " + cd); Object content = null; if (ct != null) { doc.add(Field.Keyword(F_CT, ct)); } doc.add(Field.Keyword("type", "MAIL")); if (cd != null) { doc.add(Field.Keyword(F_CD, cd)); } if (ct != null && ct.toLowerCase().startsWith("image/")) { // no point for now but maybe in the future we see if any forms such as jpegs have some strings return; } try { // get content object, indirectly calls into JAF which decodes based on MIME type and char content = p.getContent(); } catch (IOException ioe) { log.warn("OUCH decoding attachment, p=" + p, ioe); doc.add(Field.Text(F_CONTENTS, new InputStreamReader(p.getInputStream()))); return; } if (content instanceof MimeMultipart) { int n = ((MimeMultipart) content).getCount(); for (int i = 0; i < n; i++) { BodyPart bp = ((MimeMultipart) content).getBodyPart(i); // same thing ends up happening regardless, if/else left it to show structure indexPart(doc, bp); } } else if (content instanceof MimePart) { indexPart(doc, (MimePart) content); } else if (content instanceof Part) { indexPart(doc, (Part) content); } else if (content instanceof String) { indexString(doc, (String) content, ct); } else if (content instanceof InputStream) { indexStream(doc, (InputStream) content, ct); } else { log.error("***** Strange content: " + content + "/" + content.getClass() + " ct=" + ct + " cd=" + cd); } }
From source file:com.stimulus.archiva.extraction.MessageExtraction.java
private static void dumpPart(Part p, Hashtable<String, Part> attachments, Hashtable<String, String> inlines, Hashtable<String, String> images, Hashtable<String, String> nonImages, ArrayList<String> mimeTypes, String subject) throws Exception { mimeTypes.add(p.getContentType());/*from w w w .ja va2s.c o m*/ if (!p.isMimeType("multipart/*")) { String disp = p.getDisposition(); String fname = p.getFileName(); if (fname != null) { try { fname = MimeUtility.decodeText(fname); } catch (Exception e) { logger.debug("cannot decode filename:" + e.getMessage()); } } if ((disp != null && Compare.equalsIgnoreCase(disp, Part.ATTACHMENT)) || fname != null) { String filename = getFilename(subject, p); if (!filename.equalsIgnoreCase("winmail.dat")) { attachments.put(filename, p); } /*if (p.isMimeType("image/*")) { String str[] = p.getHeader("Content-ID"); if (str != null) images.put(filename,str[0]); else images.put(filename, filename); } return;*/ } } if (p.isMimeType("text/plain")) { String str = ""; if (inlines.containsKey("text/plain")) str = (String) inlines.get("text/plain") + "\n\n-------------------------------\n"; inlines.put("text/plain", str + getTextContent(p)); } else if (p.isMimeType("text/html")) { inlines.put("text/html", getTextContent(p)); } else if (p.isMimeType("text/xml")) { attachments.put(getFilename(subject, p), p); } else if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); for (int i = 0; i < mp.getCount(); i++) dumpPart(mp.getBodyPart(i), attachments, inlines, images, nonImages, mimeTypes, subject); } else if (p.isMimeType("message/rfc822")) { dumpPart((Part) p.getContent(), attachments, inlines, images, nonImages, mimeTypes, subject); } else if (p.isMimeType("application/ms-tnef")) { Part tnefpart = TNEFMime.convert(null, p, false); if (tnefpart != null) { dumpPart((Part) tnefpart, attachments, inlines, images, nonImages, mimeTypes, subject); } } else if (p.isMimeType("application/*")) { String filename = getFilename("application", p); attachments.put(filename, p); String str[] = p.getHeader("Content-ID"); if (str != null) nonImages.put(filename, str[0]); } else if (p.isMimeType("image/*")) { String fileName = getFilename("image", p); attachments.put(fileName, p); String str[] = p.getHeader("Content-ID"); if (str != null) images.put(fileName, str[0]); else images.put(fileName, fileName); } else { String contentType = p.getContentType(); Object o = p.getContent(); if (o instanceof String) { String str = ""; if (inlines.containsKey("text/plain")) str = (String) inlines.get("text/plain") + "\n\n-------------------------------\n"; inlines.put(contentType, str + (String) o); } else { String fileName = getFilenameFromContentType("attach", contentType); attachments.put(fileName, p); } } }
From source file:org.pentaho.di.job.entries.getpop.MailConnection.java
private String getMessageBodyOrContentType(Part p, final boolean returnContentType) throws MessagingException, IOException { if (p.isMimeType("text/*")) { String s = (String) p.getContent(); return returnContentType ? p.getContentType() : s; }//from www . j ava 2 s. co m if (p.isMimeType("multipart/alternative")) { // prefer html text over plain text Multipart mp = (Multipart) p.getContent(); String text = null; for (int i = 0; i < mp.getCount(); i++) { Part bp = mp.getBodyPart(i); if (bp.isMimeType("text/plain")) { if (text == null) { text = getMessageBodyOrContentType(bp, returnContentType); } } } return text; } else if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); for (int i = 0; i < mp.getCount(); i++) { String s = getMessageBodyOrContentType(mp.getBodyPart(i), returnContentType); if (s != null) { return s; } } } return null; }
From source file:org.alfresco.email.server.impl.subetha.SubethaEmailMessage.java
private void parseMessagePart(Part messagePart) { try {/* ww w. j a v a2 s . c o m*/ if (messagePart.isMimeType(MIME_PLAIN_TEXT) || messagePart.isMimeType(MIME_HTML_TEXT)) { if (log.isDebugEnabled()) { log.debug("Text or HTML part was found. ContentType: " + messagePart.getContentType()); } addBody(messagePart); } else if (messagePart.isMimeType(MIME_XML_TEXT)) { if (log.isDebugEnabled()) { log.debug("XML part was found."); } addAttachment(messagePart); } else if (messagePart.isMimeType(MIME_APPLICATION)) { if (log.isDebugEnabled()) { log.debug("Application part was found."); } addAttachment(messagePart); } else if (messagePart.isMimeType(MIME_IMAGE)) { if (log.isDebugEnabled()) { log.debug("Image part was found."); } addAttachment(messagePart); } else if (messagePart.isMimeType(MIME_MULTIPART)) { // if multipart, this method will be called recursively // for each of its parts Multipart mp = (Multipart) messagePart.getContent(); int count = mp.getCount(); if (log.isDebugEnabled()) { log.debug("MULTIPART with " + count + " part(s) found. Processin each part..."); } for (int i = 0; i < count; i++) { BodyPart bp = mp.getBodyPart(i); if (bp.getContent() instanceof MimeMultipart) { // It's multipart. Recurse. parseMessagePart(bp); } else { // It's the body addBody(bp); } } if (log.isDebugEnabled()) { log.debug("MULTIPART processed."); } } else if (messagePart.isMimeType(MIME_RFC822)) { // if rfc822, call this method with its content as the part if (log.isDebugEnabled()) { log.debug("MIME_RFC822 part found. Processing inside part..."); } parseMessagePart((Part) messagePart.getContent()); if (log.isDebugEnabled()) { log.debug("MIME_RFC822 processed."); } } else { // if all else fails, put this in the attachments map. // Actually we don't know what it is. if (log.isDebugEnabled()) { log.debug("Unrecognized part was found. Put it into attachments."); } addAttachment(messagePart); } } catch (IOException e) { throw new EmailMessageException(ERR_PARSE_MESSAGE, e.getMessage()); } catch (MessagingException e) { throw new EmailMessageException(ERR_PARSE_MESSAGE, e.getMessage()); } }
From source file:com.cubusmail.mail.text.MessageTextUtil.java
/** * @param part//from w w w . j a v a 2 s. c o m * @param messageHandler * @param loadImages * @param reply * @throws MessagingException * @throws IOException */ public static void messageTextFromPart(Part part, MessageHandler messageHandler, boolean loadImages, MessageTextMode mode, Preferences preferences, int level) throws MessagingException, IOException { log.debug("Content type of part: " + part.getContentType()); if (mode == MessageTextMode.DISPLAY || mode == MessageTextMode.DRAFT) { if (MessageUtils.isImagepart(part)) { messageHandler.setMessageImageHtml(createImageMessageText(messageHandler.getId())); } else if (!preferences.isShowHtml() && !StringUtils.isEmpty(messageHandler.getMessageTextPlain())) { return; } else if (preferences.isShowHtml() && !StringUtils.isEmpty(messageHandler.getMessageTextHtml())) { return; } else if (part.isMimeType("text/plain")) { String text = readPart(part); if (!StringUtils.isBlank(text)) { messageHandler.setMessageTextPlain(formatPlainText(text, mode)); } } else if (part.isMimeType("text/html")) { if (preferences.isShowHtml()) { String text = readPart(part); boolean[] hasImages = new boolean[] { false }; if (!StringUtils.isBlank(convertHtml2PlainText(text))) { text = formatHTMLText(text, loadImages, hasImages); messageHandler.setMessageTextHtml(text); messageHandler.setHtmlMessage(true); messageHandler.setHasImages(hasImages[0]); } } else { // only if there is no plain text part found if (StringUtils.isEmpty(messageHandler.getMessageTextPlain())) { String text = readPart(part); text = convertHtml2PlainText(text); if (!StringUtils.isBlank(text)) { text = formatPlainText(text, mode); messageHandler.setMessageTextPlain(text); } } } } else if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) { Part subPart = mp.getBodyPart(i); messageTextFromPart(subPart, messageHandler, loadImages, mode, preferences, level++); } } } else if (mode == MessageTextMode.REPLY) { if (!preferences.isCreateHtmlMsgs() && !StringUtils.isEmpty(messageHandler.getMessageTextPlain())) { return; } else if (preferences.isCreateHtmlMsgs() && !StringUtils.isEmpty(messageHandler.getMessageTextHtml())) { return; } else if (part.isMimeType("text/plain")) { String text = readPart(part); text = quotePlainText(text); if (preferences.isCreateHtmlMsgs()) { text = convertPlainText2Html(text, mode); messageHandler.setMessageTextHtml(text); messageHandler.setHtmlMessage(true); } else { messageHandler.setMessageTextPlain(text); } } else if (part.isMimeType("text/html") && StringUtils.isEmpty(messageHandler.getMessageTextPlain())) { String text = readPart(part); text = convertHtml2PlainText(text); text = quotePlainText(text); if (preferences.isCreateHtmlMsgs()) { text = convertPlainText2Html(text, mode); messageHandler.setMessageTextHtml(text); messageHandler.setHtmlMessage(true); } else { messageHandler.setMessageTextPlain(text); } } else if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) { Part subPart = mp.getBodyPart(i); messageTextFromPart(subPart, messageHandler, loadImages, mode, preferences, level++); } } } }
From source file:search.java
public static void dumpPart(Part p) throws Exception { if (p instanceof Message) { Message m = (Message) p;// w w w. j a va2 s . c om Address[] a; // FROM if ((a = m.getFrom()) != null) { for (int j = 0; j < a.length; j++) System.out.println("FROM: " + a[j].toString()); } // TO if ((a = m.getRecipients(Message.RecipientType.TO)) != null) { for (int j = 0; j < a.length; j++) System.out.println("TO: " + a[j].toString()); } // SUBJECT System.out.println("SUBJECT: " + m.getSubject()); // DATE Date d = m.getSentDate(); System.out.println("SendDate: " + (d != null ? d.toLocaleString() : "UNKNOWN")); // FLAGS: Flags flags = m.getFlags(); StringBuffer sb = new StringBuffer(); Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags boolean first = true; for (int i = 0; i < sf.length; i++) { String s; Flags.Flag f = sf[i]; if (f == Flags.Flag.ANSWERED) s = "\\Answered"; else if (f == Flags.Flag.DELETED) s = "\\Deleted"; else if (f == Flags.Flag.DRAFT) s = "\\Draft"; else if (f == Flags.Flag.FLAGGED) s = "\\Flagged"; else if (f == Flags.Flag.RECENT) s = "\\Recent"; else if (f == Flags.Flag.SEEN) s = "\\Seen"; else continue; // skip it if (first) first = false; else sb.append(' '); sb.append(s); } String[] uf = flags.getUserFlags(); // get the user flag strings for (int i = 0; i < uf.length; i++) { if (first) first = false; else sb.append(' '); sb.append(uf[i]); } System.out.println("FLAGS = " + sb.toString()); } System.out.println("CONTENT-TYPE: " + p.getContentType()); /* * Dump input stream InputStream is = ((MimeMessage)m).getInputStream(); int * c; while ((c = is.read()) != -1) System.out.write(c); */ Object o = p.getContent(); if (o instanceof String) { System.out.println("This is a String"); System.out.println((String) o); } else if (o instanceof Multipart) { System.out.println("This is a Multipart"); Multipart mp = (Multipart) o; int count = mp.getCount(); for (int i = 0; i < count; i++) dumpPart(mp.getBodyPart(i)); } else if (o instanceof InputStream) { System.out.println("This is just an input stream"); InputStream is = (InputStream) o; int c; while ((c = is.read()) != -1) System.out.write(c); } }