List of usage examples for javax.mail Part writeTo
public void writeTo(OutputStream os) throws IOException, MessagingException;
From source file:mitm.common.mail.MailUtils.java
/** * Checks whether the message can be converted to RFC2822 raw message source. Messages that * contain unsupported encoding types, corrupts content transfer encoding etc. will result * in a MessagingException or IOException. * @param message/*from w ww .ja va 2 s . c o m*/ * @throws MessagingException * @throws IOException */ public static void validateMessage(Part part) throws MessagingException, IOException { OutputStream bitsink = new OutputStream() { @Override public void write(int ignore) { } }; part.writeTo(bitsink); }
From source file:mitm.common.mail.MailUtils.java
/** * Returns the Part as a byte array. The Part is converted to a byte array using MimeMessage.writeTo. * If a message contains a corrupt body (like incorrect base64) writeTo can throw an exception. *///from w w w.j a va 2s . c o m public static byte[] partToByteArray(Part part) throws IOException, MessagingException { /* * create a buffer with some 'guess' of the size plus some constant value. If size is unknown size = -1 so * the buffer will be 1023. */ ByteArrayOutputStream bos = new ByteArrayOutputStream(part.getSize() + 1024); part.writeTo(bos); return bos.toByteArray(); }
From source file:com.stimulus.archiva.extraction.MessageExtraction.java
private static String getTextContent(Part p) throws IOException, MessagingException { try {//from www. j a v a 2s . c o m return (String) p.getContent(); } catch (UnsupportedEncodingException e) { OutputStream os = new ByteArrayOutputStream(); p.writeTo(os); String raw = os.toString(); os.close(); //cp932 -> Windows-31J raw = raw.replaceAll("cp932", "Windows-31J"); InputStream is = new ByteArrayInputStream(raw.getBytes()); Part newPart = new MimeBodyPart(is); is.close(); return (String) newPart.getContent(); } }
From source file:com.zimbra.cs.util.SpamExtract.java
private static void writeAttachedMessages(MimeMessage mm, File outdir, String msgUri) throws IOException, MessagingException { // Not raw - ignore the spam report and extract messages that are in attachments... if (!(mm.getContent() instanceof MimeMultipart)) { LOG.warn("Spam/notspam messages must have attachments (skipping " + msgUri + ")"); return;//from w w w . j av a2s.c o m } MimeMultipart mmp = (MimeMultipart) mm.getContent(); int nAttachments = mmp.getCount(); boolean foundAtleastOneAttachedMessage = false; for (int i = 0; i < nAttachments; i++) { BodyPart bp = mmp.getBodyPart(i); if (!bp.isMimeType("message/rfc822")) { // Let's ignore all parts that are not messages. continue; } foundAtleastOneAttachedMessage = true; Part msg = (Part) bp.getContent(); // the actual message File file = new File(outdir, mOutputPrefix + "-" + mExtractIndex++); OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(file)); if (msg instanceof MimeMessage) { //bug 74435 clone into newMsg so our parser has a chance to handle headers which choke javamail ZMimeMessage newMsg = new ZMimeMessage((MimeMessage) msg); newMsg.writeTo(os); } else { msg.writeTo(os); } } finally { os.close(); } if (verbose) LOG.info("Wrote: " + file); } if (!foundAtleastOneAttachedMessage) { String msgid = mm.getHeader("Message-ID", " "); LOG.warn("message uri=" + msgUri + " message-id=" + msgid + " had no attachments"); } }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Writes a passed payload part to the passed message object. *///w w w . jav a 2s . 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:edu.stanford.muse.email.EmailFetcherStats.java
/** * this method returns the text content of the message as a list of strings * // each element of the list could be the content of a multipart message * // m is the top level subject//from w ww .ja v a 2s .c om * // p is the specific part that we are processing (p could be == m) * also sets up names of attachments (though it will not download the * attachment unless downloadAttachments is true) */ private List<String> processMessagePart(int messageNum, Message m, Part p, List<Blob> attachmentsList) throws MessagingException, IOException { List<String> list = new ArrayList<String>(); // return list if (p == null) { dataErrors.add("part is null: " + folder_name() + " idx " + messageNum); return list; } if (p == m && p.isMimeType("text/html")) { /* String s = "top level part is html! message:" + m.getSubject() + " " + m.getDescription(); dataErrors.add(s); */ // we don't normally expect the top-level part to have content-type text/html // but we saw this happen on some sample archives pst -> emailchemy. so allow it and handle it by parsing the html String html = (String) p.getContent(); String text = Util.unescapeHTML(html); org.jsoup.nodes.Document doc = Jsoup.parse(text); StringBuilder sb = new StringBuilder(); HTMLUtils.extractTextFromHTML(doc.body(), sb); list.add(sb.toString()); return list; } if (p.isMimeType("text/plain")) { //make sure, p is not wrongly labelled as plain text. Enumeration headers = p.getAllHeaders(); boolean dirty = false; if (headers != null) while (headers.hasMoreElements()) { Header h = (Header) headers.nextElement(); String name = h.getName(); String value = h.getValue(); if (name != null && value != null) { if (name.equals("Content-transfer-encoding") && value.equals("base64")) { dirty = true; break; } } } String fname = p.getFileName(); if (fname != null) { int idx = fname.lastIndexOf('.'); if ((idx < fname.length()) && (idx >= 0)) { String extension = fname.substring(idx); //anything extension other than .txt is suspicious. if (!extension.equals(".txt")) dirty = true; } } if (dirty) { dataErrors.add("Dirty message part, has conflicting message part headers." + folder_name() + " Message# " + messageNum); return list; } log.debug("Message part with content type text/plain"); String content; String type = p.getContentType(); // new InputStreamReader(p.getInputStream(), "UTF-8"); try { // if forced encoding is set, we read the string with that encoding, otherwise we just use whatever p.getContent gives us if (FORCED_ENCODING != null) { byte b[] = Util.getBytesFromStream(p.getInputStream()); content = new String(b, FORCED_ENCODING); } else content = (String) p.getContent(); } catch (UnsupportedEncodingException uee) { dataErrors.add("Unsupported encoding: " + folder_name() + " Message #" + messageNum + " type " + type + ", using brute force conversion"); // a particularly nasty issue:javamail can't handle utf-7 encoding which is common with hotmail and exchange servers. // we're using the workaround suggested on this page: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4304013 // though it may be better to consider official support for utf-7 or other encodings. // TOFIX: I get an exception for utfutf8-encoding which has a base64 encoding embedded on it. // Unsupported encoding: gmail-sent Message #10477 type text/plain; charset=x-utf8utf8; name="newyorker.txt", // the hack below doesn't work for it. ByteArrayOutputStream bao = new ByteArrayOutputStream(); p.writeTo(bao); content = bao.toString(); } list.add(content); } else if (p.isMimeType("multipart/*") || p.isMimeType("message/rfc822")) { // rfc822 mime type is for embedded mbox format or some such (appears for things like // forwarded messages). the content appears to be just a multipart. Object o = p.getContent(); if (o instanceof Multipart) { Multipart allParts = (Multipart) o; if (p.isMimeType("multipart/alternative")) { // this is an alternative mime type. v common case to have text and html alternatives // so just process the text part if there is one, and avoid fetching the alternatives. // useful esp. because many ordinary messages are alternative: text and html and we don't want to fetch the html. // revisit in future we want to retain the html alternative for display purposes Part[] parts = new Part[allParts.getCount()]; for (int i = 0; i < parts.length; i++) parts[i] = allParts.getBodyPart(i); for (int i = 0; i < parts.length; i++) { Part thisPart = parts[i]; if (thisPart.isMimeType("text/plain")) { // common case, return quickly list.add((String) thisPart.getContent()); log.debug("Multipart/alternative with content type text/plain"); return list; } } // no text part, let's look for an html part. this happens for html parts. for (int i = 0; i < allParts.getCount(); i++) { Part thisPart = parts[i]; if (thisPart.isMimeType("text/html")) { // common case, return quickly String html = (String) thisPart.getContent(); String text = Util.unescapeHTML(html); org.jsoup.nodes.Document doc = Jsoup.parse(text); StringBuilder sb = new StringBuilder(); HTMLUtils.extractTextFromHTML(doc.body(), sb); list.add(sb.toString()); log.debug("Multipart/alternative with content type text/html"); return list; } } // no text or html part. hmmm... blindly process the first part only if (allParts.getCount() >= 1) list.addAll(processMessagePart(messageNum, m, allParts.getBodyPart(0), attachmentsList)); } else { // process it like a regular multipart for (int i = 0; i < allParts.getCount(); i++) { BodyPart bp = allParts.getBodyPart(i); list.addAll(processMessagePart(messageNum, m, bp, attachmentsList)); } } } else if (o instanceof Part) list.addAll(processMessagePart(messageNum, m, (Part) o, attachmentsList)); else dataErrors.add("Unhandled part content, " + folder_name() + " Message #" + messageNum + "Java type: " + o.getClass() + " Content-Type: " + p.getContentType()); } else { try { // do attachments only if downloadAttachments is set. // some apps do not need attachments, so this saves some time. // however, it seems like a lot of time is taken in imap prefetch, which gets attachments too? if (fetchConfig.downloadAttachments) handleAttachments(messageNum, m, p, list, attachmentsList); } catch (Exception e) { dataErrors.add("Ignoring attachment for " + folder_name() + " Message #" + messageNum + ": " + Util.stackTrace(e)); } } return list; }
From source file:org.apache.james.transport.mailets.StripAttachment.java
private boolean checkMessageRemoved(Part part, Mail mail) throws MessagingException, Exception { String fileName;//from w w w . j a v a 2 s . co m fileName = part.getFileName(); // filename or name of part can be null, so we have to be careful boolean ret = false; if (fileName != null) { if (decodeFilename) fileName = MimeUtility.decodeText(fileName); if (filenameReplacingPatterns != null) fileName = new ContentReplacer(false, this).applyPatterns(filenameReplacingPatterns, fileName); if (fileNameMatches(fileName)) { if (directoryName != null) { String filename = saveAttachmentToFile(part, fileName); if (filename != null) { @SuppressWarnings("unchecked") Collection<String> c = (Collection<String>) mail .getAttribute(SAVED_ATTACHMENTS_ATTRIBUTE_KEY); if (c == null) { c = new ArrayList<String>(); mail.setAttribute(SAVED_ATTACHMENTS_ATTRIBUTE_KEY, (ArrayList<String>) c); } c.add(filename); } } if (attributeName != null) { @SuppressWarnings("unchecked") Map<String, byte[]> m = (Map<String, byte[]>) mail.getAttribute(attributeName); if (m == null) { m = new LinkedHashMap<String, byte[]>(); mail.setAttribute(attributeName, (LinkedHashMap<String, byte[]>) m); } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStream os = new BufferedOutputStream(byteArrayOutputStream); part.writeTo(os); m.put(fileName, byteArrayOutputStream.toByteArray()); } if (removeAttachments.equals(REMOVE_MATCHED)) { ret = true; } } if (!ret) { ret = removeAttachments.equals(REMOVE_ALL); } if (ret) { @SuppressWarnings("unchecked") Collection<String> c = (Collection<String>) mail.getAttribute(REMOVED_ATTACHMENTS_ATTRIBUTE_KEY); if (c == null) { c = new ArrayList<String>(); mail.setAttribute(REMOVED_ATTACHMENTS_ATTRIBUTE_KEY, (ArrayList<String>) c); } c.add(fileName); } } return ret; }