List of usage examples for javax.mail Part isMimeType
public boolean isMimeType(String mimeType) throws MessagingException;
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 w w w.ja v a2 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:edu.stanford.muse.email.EmailFetcherStats.java
private List<String> getAttachmentNames(MimeMessage m, Part p) throws MessagingException, IOException { List<String> result = new ArrayList<String>(); try {// w ww . j av a 2 s . c o m if (p.isMimeType("multipart/*") || p.isMimeType("message/rfc822")) { if (p.isMimeType("multipart/alternative")) return result; // ignore alternative's because real attachments don't have alternatives DataHandler dh = p.getDataHandler(); DataSource ds = dh.getDataSource(); if (ds instanceof MultipartDataSource) { MultipartDataSource mpds = (MultipartDataSource) ds; for (int i = 0; i < mpds.getCount(); i++) result.addAll(getAttachmentNames(m, mpds.getBodyPart(i))); } else { String name = ds.getName(); if (!Util.nullOrEmpty(name)) result.add(name); } } else { String filename = p.getFileName(); if (filename != null) result.add(filename); } } catch (Exception e) { // sometimes we see javax.mail.MessagingException: Unable to load BODYSTRUCTURE // in this case, just ignore, not much we can do i guess. Util.print_exception(e, log); } return result; }
From source file:org.sakaiproject.james.SakaiMailet.java
/** * Breaks email messages into parts which can be saved as files (saves as attachments) or viewed as plain text (added to body of message). * /*from w w w.j av a2 s .c o m*/ * @param siteId * Site associated with attachments, if any * @param p * The message-part embedded in a message.. * @param id * The string containing the message's id. * @param bodyBuf * The string-buffers in which the plain/text and/or html/text message body is being built. * @param bodyContentType * The value of the Content-Type header for the mesage body. * @param attachments * The ReferenceVector in which references to attachments are collected. * @param embedCount * An Integer that counts embedded messages (outer message is zero). * @return Value of embedCount (updated if this call processed any embedded messages). */ protected Integer parseParts(String siteId, Part p, String id, StringBuilder bodyBuf[], StringBuilder bodyContentType, List attachments, Integer embedCount) throws MessagingException, IOException { // increment embedded message counter if (p instanceof Message) { embedCount = Integer.valueOf(embedCount.intValue() + 1); } String type = p.getContentType(); // discard if content-type is unknown if (type == null || "".equals(type)) { M_log.warn(this + " message with unknown content-type discarded"); } // add plain text to bodyBuf[0] else if (p.isMimeType("text/plain") && p.getFileName() == null) { Object o = null; // let them convert to text if possible // but if bad encaps get the stream and do it ourselves try { o = p.getContent(); } catch (java.io.UnsupportedEncodingException ignore) { o = p.getInputStream(); } String txt = null; String innerContentType = p.getContentType(); if (o instanceof String) { txt = (String) p.getContent(); if (bodyContentType != null && bodyContentType.length() == 0) bodyContentType.append(innerContentType); } else if (o instanceof InputStream) { InputStream in = (InputStream) o; ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[in.available()]; for (int len = in.read(buf); len != -1; len = in.read(buf)) out.write(buf, 0, len); String charset = (new ContentType(innerContentType)).getParameter("charset"); // RFC 2045 says if no char set specified use US-ASCII. // If specified but illegal that's less clear. The common case is X-UNKNOWN. // my sense is that UTF-8 is most likely these days but the sample we got // was actually ISO 8859-1. Could also justify using US-ASCII. Duh... if (charset == null) charset = "us-ascii"; try { txt = out.toString(MimeUtility.javaCharset(charset)); } catch (java.io.UnsupportedEncodingException ignore) { txt = out.toString("UTF-8"); } if (bodyContentType != null && bodyContentType.length() == 0) bodyContentType.append(innerContentType); } // remove extra line breaks added by mac Mail, perhaps others // characterized by a space followed by a line break if (txt != null) { txt = txt.replaceAll(" \n", " "); } // make sure previous message parts ended with newline if (bodyBuf[0].length() > 0 && bodyBuf[0].charAt(bodyBuf[0].length() - 1) != '\n') bodyBuf[0].append("\n"); bodyBuf[0].append(txt); } // add html text to bodyBuf[1] else if (p.isMimeType("text/html") && p.getFileName() == null) { Object o = null; // let them convert to text if possible // but if bad encaps get the stream and do it ourselves try { o = p.getContent(); } catch (java.io.UnsupportedEncodingException ignore) { o = p.getInputStream(); } String txt = null; String innerContentType = p.getContentType(); if (o instanceof String) { txt = (String) p.getContent(); if (bodyContentType != null && bodyContentType.length() == 0) bodyContentType.append(innerContentType); } else if (o instanceof InputStream) { InputStream in = (InputStream) o; ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[in.available()]; for (int len = in.read(buf); len != -1; len = in.read(buf)) out.write(buf, 0, len); String charset = (new ContentType(innerContentType)).getParameter("charset"); if (charset == null) charset = "us-ascii"; try { txt = out.toString(MimeUtility.javaCharset(charset)); } catch (java.io.UnsupportedEncodingException ignore) { txt = out.toString("UTF-8"); } if (bodyContentType != null && bodyContentType.length() == 0) bodyContentType.append(innerContentType); } // remove bad image tags and naughty javascript if (txt != null) { txt = Web.cleanHtml(txt); } bodyBuf[1].append(txt); } // process subparts of multiparts else if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) { embedCount = parseParts(siteId, mp.getBodyPart(i), id, bodyBuf, bodyContentType, attachments, embedCount); } } // Discard parts with mime-type application/applefile. If an e-mail message contains an attachment is sent from // a macintosh, you may get two parts, one for the data fork and one for the resource fork. The part that // corresponds to the resource fork confuses users, this has mime-type application/applefile. The best thing // is to discard it. else if (p.isMimeType("application/applefile")) { M_log.warn(this + " message with application/applefile discarded"); } // discard enriched text version of the message. // Sakai only uses the plain/text or html/text version of the message. else if (p.isMimeType("text/enriched") && p.getFileName() == null) { M_log.warn(this + " message with text/enriched discarded"); } // everything else gets treated as an attachment else { String name = p.getFileName(); // look for filenames not parsed by getFileName() if (name == null && type.indexOf(NAME_PREFIX) != -1) { name = type.substring(type.indexOf(NAME_PREFIX) + NAME_PREFIX.length()); } // ContentType can't handle filenames with spaces or UTF8 characters if (name != null) { String decodedName = MimeUtility.decodeText(name); // first decode RFC 2047 type = type.replace(name, URLEncoder.encode(decodedName, "UTF-8")); name = decodedName; } ContentType cType = new ContentType(type); String disposition = p.getDisposition(); int approxSize = p.getSize(); if (name == null) { name = "unknown"; // if file's parent is multipart/alternative, // provide a better name for the file if (p instanceof BodyPart) { Multipart parent = ((BodyPart) p).getParent(); if (parent != null) { String pType = parent.getContentType(); ContentType pcType = new ContentType(pType); if (pcType.getBaseType().equalsIgnoreCase("multipart/alternative")) { name = "message" + embedCount; } } } if (p.isMimeType("text/html")) { name += ".html"; } else if (p.isMimeType("text/richtext")) { name += ".rtx"; } else if (p.isMimeType("text/rtf")) { name += ".rtf"; } else if (p.isMimeType("text/enriched")) { name += ".etf"; } else if (p.isMimeType("text/plain")) { name += ".txt"; } else if (p.isMimeType("text/xml")) { name += ".xml"; } else if (p.isMimeType("message/rfc822")) { name += ".txt"; } } // read the attachments bytes, and create it as an attachment in content hosting byte[] bodyBytes = readBody(approxSize, p.getInputStream()); if ((bodyBytes != null) && (bodyBytes.length > 0)) { // can we ignore the attachment it it's just whitespace chars?? Reference attachment = createAttachment(siteId, attachments, cType.getBaseType(), name, bodyBytes, id); // add plain/text attachment reference (if plain/text message) if (attachment != null && bodyBuf[0].length() > 0) bodyBuf[0] .append("[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]\n\n"); // add html/text attachment reference (if html/text message) if (attachment != null && bodyBuf[1].length() > 0) bodyBuf[1].append( "<p>[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]</p>"); // add plain/text attachment reference (if no plain/text and no html/text) if (attachment != null && bodyBuf[0].length() == 0 && bodyBuf[1].length() == 0) bodyBuf[0] .append("[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]\n\n"); } } return embedCount; }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
/** * Extract/format mail message content.//from w w w. java 2 s. c o m * * @param msg * @return */ private String fetchMsgContent(Message msg) throws Exception { String content = null; String html = null; String text = null; if (msg.isMimeType("multipart/*")) { Multipart mp = (Multipart) msg.getContent(); // the content was not fetched from the server // parse each Part for (int i = 0; i < mp.getCount(); i++) { Part inner_part = mp.getBodyPart(i); if (inner_part.isMimeType("text/plain")) { text = (String) inner_part.getContent(); System.out.println("TEXT=\n" + text); } else if (inner_part.isMimeType("text/html")) { html = (String) inner_part.getContent(); System.out.println("HTML=\n" + content); } } } else if (msg.isMimeType("text/plain")) { text = (String) msg.getContent(); System.out.println("TEXT only=\n" + text); } if (!CommonUtil.strNullorEmpty(html)) { content = html; } else { content = text; } return content; }
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// ww w . ja v a 2 s. 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.SMIMEDecrypt.java
/** * @see org.apache.mailet.Mailet#service(org.apache.mailet.Mail) *///from w ww. j av a 2s. c om @SuppressWarnings("unchecked") public void service(Mail mail) throws MessagingException { MimeMessage message = mail.getMessage(); Part strippedMessage = null; log("Starting message decryption.."); if (message.isMimeType("application/x-pkcs7-mime") || message.isMimeType("application/pkcs7-mime")) { try { SMIMEEnveloped env = new SMIMEEnveloped(message); RecipientInformationStore informationStore = env.getRecipientInfos(); Collection<RecipientInformation> recipients = informationStore.getRecipients(); for (RecipientInformation info : recipients) { RecipientId id = info.getRID(); if (id.match(certificateHolder)) { try { JceKeyTransEnvelopedRecipient recipient = new JceKeyTransEnvelopedRecipient( keyHolder.getPrivateKey()); // strippedMessage contains the decrypted message. strippedMessage = SMIMEUtil.toMimeBodyPart(info.getContent(recipient)); log("Encrypted message decrypted"); } catch (Exception e) { throw new MessagingException("Error during the decryption of the message", e); } } else { log("Found an encrypted message but it isn't encrypted for the supplied key"); } } } catch (CMSException e) { throw new MessagingException("Error during the decryption of the message", e); } } // if the decryption has been successful.. if (strippedMessage != null) { // I put the private key's public certificate as a mailattribute. // I create a list of certificate because I want to minic the // behavior of the SMIMEVerifySignature mailet. In that way // it is possible to reuse the same matchers to analyze // the result of the operation. ArrayList<X509Certificate> list = new ArrayList<X509Certificate>(1); list.add(keyHolder.getCertificate()); mail.setAttribute(mailAttribute, list); // I start the message stripping. try { MimeMessage newMessage = new MimeMessage(message); newMessage.setText(text(strippedMessage), Charsets.UTF_8.name()); if (!strippedMessage.isMimeType("multipart/*")) { newMessage.setDisposition(null); } newMessage.saveChanges(); mail.setMessage(newMessage); } catch (IOException e) { log("Error during the strip of the encrypted message"); throw new MessagingException("Error during the stripping of the encrypted message", e); } } }
From source file:edu.stanford.muse.email.EmailFetcherStats.java
/** * recursively processes attachments, fetching and saving it if needed * parses the given part p, and adds it to hte attachmentsList. * in some cases, like a text/html type without a filename, we instead append it to the textlist * @throws MessagingException/*from w w w . j av a2 s. c om*/ */ private void handleAttachments(int idx, Message m, Part p, List<String> textList, List<Blob> attachmentsList) throws MessagingException { String ct = null; if (!(m instanceof MimeMessage)) { Exception e = new IllegalArgumentException("Not a MIME message!"); e.fillInStackTrace(); log.warn(Util.stackTrace(e)); return; } String filename = null; try { filename = p.getFileName(); } catch (Exception e) { // seen this happen with: // Folders__gmail-sent Message #12185 Expected ';', got "Message" // javax.mail.internet.ParseException: Expected ';', got "Message" dataErrors.add("Unable to read attachment name: " + folder_name() + " Message# " + idx); return; } String sanitizedFName = Util.sanitizeFolderName(emailStore.getAccountID() + "." + folder_name()); if (filename == null) { String tempFname = sanitizedFName + "." + idx; dataErrors.add("attachment filename is null for " + sanitizedFName + " Message#" + idx + " assigning it the name: " + tempFname); if (p.isMimeType("text/html")) { try { log.info("Turning message " + sanitizedFName + " Message#" + idx + " into text although it is an attachment"); 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); textList.add(sb.toString()); return; } catch (Exception e) { Util.print_exception("Error reading contents of text/html multipart without a filename!", e, log); return; } } filename = tempFname; } // Replacing any of the disallowed filename characters (\/:*?"<>|&) to _ // (note: & causes problems with URLs for serveAttachment etc, so it's also replaced) String newFilename = Util.sanitizeFileName(filename); // Updating filename if it's changed after sanitizing. if (!newFilename.equals(filename)) { log.info("Filename changed from " + filename + " to " + newFilename); filename = newFilename; } try { ct = p.getContentType(); if (filename.indexOf(".") < 0) // no ext in filename... let's fix it if possible { // Using startsWith instead of equals because sometimes the ct has crud beyond the image/jpeg;...crud.... // Below are the most common file types, more type can be added if needed // Most common APPLICATION TYPE if (ct.startsWith("application/pdf")) filename = filename + ".pdf"; if (ct.startsWith("application/zip")) filename = filename + ",zip"; // Most common IMAGE TYPE if (ct.startsWith("image/jpeg")) filename = filename + ".jpg"; if (ct.startsWith("image/gif")) filename = filename + ".gif"; if (ct.startsWith("image/png")) filename = filename + ".png"; // Most Common VIDEO TYPE if (ct.startsWith("video/x-ms-wmv")) filename = filename + ".wmv"; // Most Common AUDIO TYPE if (ct.startsWith("audio/mpeg")) filename = filename + ".mp3"; if (ct.startsWith("audio/mp4")) filename = filename + ".mp4"; // Most Common TEXT TYPE if (ct.startsWith("text/html")) filename = filename + ".html"; // Windows Office if (ct.startsWith("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) //Word filename = filename + ".docx"; if (ct.startsWith("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) //Excel filename = filename + ".xlsx"; if (ct.startsWith("application/vnd.openxmlformats-officedocument.presentationml.presentation")) //PowerPoint filename = filename + ".pptx"; } // retain only up to first semi-colon; often ct is something like text/plain; name="filename"' we don't want to log the filename int x = ct.indexOf(";"); if (x >= 0) ct = ct.substring(0, x); log.info("Attachment content type: " + ct + " filename = " + Util.blurKeepingExtension(filename)); } catch (Exception pex) { dataErrors.add("Can't read CONTENT-TYPE: " + ct + " filename:" + filename + " size = " + p.getSize() + " subject: " + m.getSubject() + " Date : " + m.getSentDate().toString() + "\n Exception: " + pex + "\n" + Util.stackTrace(pex)); return; } // if (filename == null && !p.isMimeType("text/html") && !p.isMimeType("message/partial")) // expected not to have a filename with mime type text/html // log.warn ("Attachment filename is null: " + Util.stackTrace()); boolean success = true; // the size passed in here is the part size, which is not really the binary blob size. // when we read the stream below in blobStore.add(), we'll set it again to the binary blob size Blob b = new EmailAttachmentBlob(filename, p.getSize(), (MimeMessage) m, p); if (fetchConfig.downloadAttachments) { // this containment check is only on the basis of file name and size currently, // not on the actual hash if (archive.getBlobStore().contains(b)) { log.debug("Cache hit! " + b); } else { try { if (filename.endsWith(".tif")) log.info("Fetching attachment..." + Util.blurKeepingExtension(filename)); // performance critical! use large buffer! currently 256KB // stream will be closed by callee long start = System.currentTimeMillis(); long nBytes = archive.getBlobStore().add(b, new BufferedInputStream(p.getInputStream(), 256 * 1024)); long end = System.currentTimeMillis(); if (nBytes != -1) { long diff = end - start; String s = "attachment size " + nBytes + " bytes, fetched in " + diff + " millis"; if (diff > 0) s += " (" + (nBytes / diff) + " KB/s)"; log.info(s); } Util.ASSERT(archive.getBlobStore().contains(b)); } catch (IOException ioe) { success = false; dataErrors.add("WARNING: Unable to fetch attachment: filename: " + filename + " size = " + p.getSize() + " subject: " + m.getSubject() + " Date : " + m.getSentDate().toString() + "\nException: " + ioe); ioe.printStackTrace(System.out); } } if (success) { attachmentsList.add(b); /// generate thumbnail only if not already cached try { archive.getBlobStore().generate_thumbnail(b); // supplement } catch (IOException ioe) { log.warn("failed to create thumbnail, filename: " + filename + " size = " + p.getSize() + " subject: " + m.getSubject() + " Date : " + m.getSentDate().toString() + "\nException: " + ioe); ioe.printStackTrace(System.out); } } } }
From source file:com.sonicle.webtop.mail.Service.java
public void processGetForwardMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {/* ww w . j a va2 s. c o m*/ MailAccount account = getAccount(request); UserProfile profile = environment.getProfile(); String pfoldername = request.getParameter("folder"); String puidmessage = request.getParameter("idmessage"); String pnewmsgid = request.getParameter("newmsgid"); String pattached = request.getParameter("attached"); boolean attached = (pattached != null && pattached.equals("1")); long newmsgid = Long.parseLong(pnewmsgid); String sout = null; try { String format = us.getFormat(); boolean isHtml = format.equals("html"); account.checkStoreConnected(); FolderCache mcache = account.getFolderCache(pfoldername); Message m = mcache.getMessage(Long.parseLong(puidmessage)); if (m.isExpunged()) { throw new MessagingException("Message " + puidmessage + " expunged"); } SimpleMessage smsg = getForwardMsg(newmsgid, m, isHtml, lookupResource(MailLocaleKey.MSG_FROMTITLE), lookupResource(MailLocaleKey.MSG_TOTITLE), lookupResource(MailLocaleKey.MSG_CCTITLE), lookupResource(MailLocaleKey.MSG_DATETITLE), lookupResource(MailLocaleKey.MSG_SUBJECTTITLE), attached); sout = "{\n result: true,"; Identity ident = mprofile.getIdentity(pfoldername); String forwardedfrom = smsg.getForwardedFrom(); sout += " forwardedfolder: '" + StringEscapeUtils.escapeEcmaScript(pfoldername) + "',"; if (forwardedfrom != null) { sout += " forwardedfrom: '" + StringEscapeUtils.escapeEcmaScript(forwardedfrom) + "',"; } String subject = smsg.getSubject(); sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n"; String html = smsg.getContent(); String text = smsg.getTextContent(); if (!attached) { HTMLMailData maildata = mcache.getMailData((MimeMessage) m); boolean first = true; sout += " attachments: [\n"; for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) { try { Part part = maildata.getAttachmentPart(i); String filename = getPartName(part); if (!part.isMimeType("message/*")) { String cids[] = part.getHeader("Content-ID"); String cid = null; //String cid=filename; if (cids != null && cids[0] != null) { cid = cids[0]; if (cid.startsWith("<")) cid = cid.substring(1); if (cid.endsWith(">")) cid = cid.substring(0, cid.length() - 1); } if (filename == null) filename = cid; String mime = MailUtils.getMediaTypeFromHeader(part.getContentType()); UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, mime, part.getInputStream()); boolean inline = false; if (part.getDisposition() != null) { inline = part.getDisposition().equalsIgnoreCase(Part.INLINE); } if (!first) { sout += ",\n"; } sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', " + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: " + (cid == null ? null : "'" + StringEscapeUtils.escapeEcmaScript(cid) + "'") + ", " + " inline: " + inline + ", " + " fileSize: " + upfile.getSize() + ", " + " editable: " + isFileEditableInDocEditor(filename) + " " + " }"; first = false; //TODO: change this weird matching of cids2urls! html = StringUtils.replace(html, "cid:" + cid, "service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId=" + upfile.getUploadId() + "&cid=" + cid); } } catch (Exception exc) { Service.logger.error("Exception", exc); } } sout += "\n ],\n"; //String surl = "service-request?service="+SERVICE_ID+"&action=PreviewAttachment&nowriter=true&newmsgid=" + newmsgid + "&cid="; //html = replaceCidUrls(html, maildata, surl); } else { String filename = m.getSubject() + ".eml"; UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, "message/rfc822", ((IMAPMessage) m).getMimeStream()); sout += " attachments: [\n"; sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', " + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: null, " + " inline: false, " + " fileSize: " + upfile.getSize() + ", " + " editable: " + isFileEditableInDocEditor(filename) + " " + " }"; sout += "\n ],\n"; } sout += " identityId: " + ident.getIdentityId() + ",\n"; sout += " origuid:" + puidmessage + ",\n"; if (isHtml) { sout += " content:'" + StringEscapeUtils.escapeEcmaScript(html) + "',\n"; } else { sout += " content:'" + StringEscapeUtils.escapeEcmaScript(text) + "',\n"; } sout += " format:'" + format + "'\n"; sout += "\n}"; out.println(sout); } catch (Exception exc) { Service.logger.error("Exception", exc); sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}"; out.println(sout); } }
From source file:com.sonicle.webtop.mail.Service.java
private boolean appendReplyParts(Part p, StringBuffer htmlsb, StringBuffer textsb, ArrayList<String> attnames) throws MessagingException, IOException { boolean isHtml = false; String disp = p.getDisposition(); if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT) && !p.isMimeType("message/*")) { if (attnames != null) {//from w ww.ja va 2s . c om String id[] = p.getHeader("Content-ID"); if (id == null || id[0] == null) { String filename = p.getFileName(); if (filename != null) { if (filename.startsWith("<")) { filename = filename.substring(1); } if (filename.endsWith(">")) { filename = filename.substring(0, filename.length() - 1); } } if (filename != null) { attnames.add(filename); } } } return false; } if (p.isMimeType("text/html")) { //String htmlcontent=(String)p.getContent(); String htmlcontent = getTextContentAsString(p); textsb.append(MailUtils.htmlToText(MailUtils.htmlunescapesource(htmlcontent))); htmlsb.append(MailUtils.htmlescapefixsource(/*getBodyInnerHtml(*/htmlcontent/*)*/)); isHtml = true; } else if (p.isMimeType("text/plain")) { String content = getTextContentAsString(p); textsb.append(content); htmlsb.append(startpre + MailUtils.htmlescape(content) + endpre); isHtml = false; } else if (p.isMimeType("message/delivery-status") || p.isMimeType("message/disposition-notification")) { InputStream is = (InputStream) p.getContent(); char cbuf[] = new char[8000]; byte bbuf[] = new byte[8000]; int n = 0; htmlsb.append(startpre); while ((n = is.read(bbuf)) >= 0) { if (n > 0) { for (int i = 0; i < n; ++i) { cbuf[i] = (char) bbuf[i]; } textsb.append(cbuf); htmlsb.append(MailUtils.htmlescape(new String(cbuf))); } } htmlsb.append(endpre); is.close(); isHtml = false; } else if (p.isMimeType("multipart/alternative")) { Multipart mp = (Multipart) p.getContent(); Part bestPart = null; for (int i = 0; i < mp.getCount(); ++i) { Part part = mp.getBodyPart(i); if (part.isMimeType("multipart/*")) { isHtml = appendReplyParts(part, htmlsb, textsb, attnames); if (isHtml) { bestPart = null; break; } } else if (part.isMimeType("text/html")) { bestPart = part; break; } else if (bestPart == null && part.isMimeType("text/plain")) { bestPart = part; } else if (bestPart == null && part.isMimeType("message/*")) { bestPart = part; } } if (bestPart != null) { isHtml = appendReplyParts(bestPart, htmlsb, textsb, attnames); } } else if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); for (int i = 0; i < mp.getCount(); ++i) { if (appendReplyParts(mp.getBodyPart(i), htmlsb, textsb, attnames)) { isHtml = true; } } } else if (p.isMimeType("message/*")) { Object content = p.getContent(); if (appendReplyParts((MimeMessage) content, htmlsb, textsb, attnames)) { isHtml = true; } } else { } textsb.append('\n'); textsb.append('\n'); return isHtml; }
From source file:com.sonicle.webtop.mail.Service.java
public void processGetMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { MailAccount account = getAccount(request); String pfoldername = request.getParameter("folder"); String puidmessage = request.getParameter("idmessage"); String pidattach = request.getParameter("idattach"); String providername = request.getParameter("provider"); String providerid = request.getParameter("providerid"); String nopec = request.getParameter("nopec"); int idattach = 0; boolean isEditor = request.getParameter("editor") != null; boolean setSeen = ServletUtils.getBooleanParameter(request, "setseen", true); if (df == null) { df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM, environment.getProfile().getLocale()); }/*from www . j a v a 2 s. co m*/ try { FolderCache mcache = null; Message m = null; IMAPMessage im = null; int recs = 0; long msguid = -1; String vheader[] = null; boolean wasseen = false; boolean isPECView = false; String sout = "{\nmessage: [\n"; if (providername == null) { account.checkStoreConnected(); mcache = account.getFolderCache(pfoldername); msguid = Long.parseLong(puidmessage); m = mcache.getMessage(msguid); im = (IMAPMessage) m; im.setPeek(us.isManualSeen()); if (m.isExpunged()) throw new MessagingException("Message " + puidmessage + " expunged"); vheader = m.getHeader("Disposition-Notification-To"); wasseen = m.isSet(Flags.Flag.SEEN); if (pidattach != null) { HTMLMailData mailData = mcache.getMailData((MimeMessage) m); Part part = mailData.getAttachmentPart(Integer.parseInt(pidattach)); m = (Message) part.getContent(); idattach = Integer.parseInt(pidattach) + 1; } else if (nopec == null && mcache.isPEC()) { String hdrs[] = m.getHeader(HDR_PEC_TRASPORTO); if (hdrs != null && hdrs.length > 0 && hdrs[0].equals("posta-certificata")) { HTMLMailData mailData = mcache.getMailData((MimeMessage) m); int parts = mailData.getAttachmentPartCount(); for (int i = 0; i < parts; ++i) { Part p = mailData.getAttachmentPart(i); if (p.isMimeType("message/rfc822")) { m = (Message) p.getContent(); idattach = i + 1; isPECView = true; break; } } } } } else { // TODO: provider get message!!!! /* WebTopService provider=wts.getServiceByName(providername); MessageContentProvider mcp=provider.getMessageContentProvider(providerid); m=new MimeMessage(session,mcp.getSource()); mcache=fcProvided; mcache.addProvidedMessage(providername, providerid, m);*/ } String messageid = getMessageID(m); String subject = m.getSubject(); if (subject == null) { subject = ""; } else { try { subject = MailUtils.decodeQString(subject); } catch (Exception exc) { } } java.util.Date d = m.getSentDate(); if (d == null) { d = m.getReceivedDate(); } if (d == null) { d = new java.util.Date(0); } String date = df.format(d).replaceAll("\\.", ":"); String fromName = ""; String fromEmail = ""; Address as[] = m.getFrom(); InternetAddress iafrom = null; if (as != null && as.length > 0) { iafrom = (InternetAddress) as[0]; fromName = iafrom.getPersonal(); fromEmail = adjustEmail(iafrom.getAddress()); if (fromName == null) { fromName = fromEmail; } } sout += "{iddata:'from',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(fromName)) + "',value2:'" + StringEscapeUtils.escapeEcmaScript(fromEmail) + "',value3:0},\n"; recs += 2; Address tos[] = m.getRecipients(RecipientType.TO); if (tos != null) { for (Address to : tos) { InternetAddress ia = (InternetAddress) to; String toName = ia.getPersonal(); String toEmail = adjustEmail(ia.getAddress()); if (toName == null) { toName = toEmail; } sout += "{iddata:'to',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(toName)) + "',value2:'" + StringEscapeUtils.escapeEcmaScript(toEmail) + "',value3:0},\n"; ++recs; } } Address ccs[] = m.getRecipients(RecipientType.CC); if (ccs != null) { for (Address cc : ccs) { InternetAddress ia = (InternetAddress) cc; String ccName = ia.getPersonal(); String ccEmail = adjustEmail(ia.getAddress()); if (ccName == null) { ccName = ccEmail; } sout += "{iddata:'cc',value1:'" + StringEscapeUtils.escapeEcmaScript(ccName) + "',value2:'" + StringEscapeUtils.escapeEcmaScript(ccEmail) + "',value3:0},\n"; ++recs; } } Address bccs[] = m.getRecipients(RecipientType.BCC); if (bccs != null) for (Address bcc : bccs) { InternetAddress ia = (InternetAddress) bcc; String bccName = ia.getPersonal(); String bccEmail = adjustEmail(ia.getAddress()); if (bccName == null) { bccName = bccEmail; } sout += "{iddata:'bcc',value1:'" + StringEscapeUtils.escapeEcmaScript(bccName) + "',value2:'" + StringEscapeUtils.escapeEcmaScript(bccEmail) + "',value3:0},\n"; ++recs; } ArrayList<String> htmlparts = null; boolean balanceTags = isPreviewBalanceTags(iafrom); if (providername == null) { htmlparts = mcache.getHTMLParts((MimeMessage) m, msguid, false, balanceTags); } else { htmlparts = mcache.getHTMLParts((MimeMessage) m, providername, providerid, balanceTags); } HTMLMailData mailData = mcache.getMailData((MimeMessage) m); ICalendarRequest ir = mailData.getICalRequest(); if (ir != null) { if (htmlparts.size() > 0) sout += "{iddata:'html',value1:'" + StringEscapeUtils.escapeEcmaScript(htmlparts.get(0)) + "',value2:'',value3:0},\n"; } else { for (String html : htmlparts) { //sout += "{iddata:'html',value1:'" + OldUtils.jsEscape(html) + "',value2:'',value3:0},\n"; sout += "{iddata:'html',value1:'" + StringEscapeUtils.escapeEcmaScript(html) + "',value2:'',value3:0},\n"; ++recs; } } /*if (!wasseen) { //if (us.isManualSeen()) { if (!setSeen) { m.setFlag(Flags.Flag.SEEN, false); } else { //if no html part, flag seen is not set if (htmlparts.size()==0) m.setFlag(Flags.Flag.SEEN, true); } }*/ if (!us.isManualSeen()) { if (htmlparts.size() == 0) m.setFlag(Flags.Flag.SEEN, true); } else { if (setSeen) m.setFlag(Flags.Flag.SEEN, true); } int acount = mailData.getAttachmentPartCount(); for (int i = 0; i < acount; ++i) { Part p = mailData.getAttachmentPart(i); String ctype = p.getContentType(); Service.logger.debug("attachment " + i + " is " + ctype); int ix = ctype.indexOf(';'); if (ix > 0) { ctype = ctype.substring(0, ix); } String cidnames[] = p.getHeader("Content-ID"); String cidname = null; if (cidnames != null && cidnames.length > 0) cidname = mcache.normalizeCidFileName(cidnames[0]); boolean isInlineable = isInlineableMime(ctype); boolean inline = ((p.getHeader("Content-Location") != null) || (cidname != null)) && isInlineable; if (inline && cidname != null) inline = mailData.isReferencedCid(cidname); if (p.getDisposition() != null && p.getDisposition().equalsIgnoreCase(Part.INLINE) && inline) { continue; } String imgname = null; boolean isCalendar = ctype.equalsIgnoreCase("text/calendar") || ctype.equalsIgnoreCase("text/icalendar"); if (isCalendar) { imgname = "resources/" + getManifest().getId() + "/laf/" + cus.getLookAndFeel() + "/ical_16.png"; } String pname = getPartName(p); try { pname = MailUtils.decodeQString(pname); } catch (Exception exc) { } if (pname == null) { ix = ctype.indexOf("/"); String fname = ctype; if (ix > 0) { fname = ctype.substring(ix + 1); } //String ext = WT.getMediaTypeExtension(ctype); //if (ext == null) { pname = fname; //} else { // pname = fname + "." + ext; //} if (isCalendar) pname += ".ics"; } else { if (isCalendar && !StringUtils.endsWithIgnoreCase(pname, ".ics")) pname += ".ics"; } int size = p.getSize(); int lines = (size / 76); int rsize = size - (lines * 2);//(p.getSize()/4)*3; String iddata = ctype.equalsIgnoreCase("message/rfc822") ? "eml" : (inline ? "inlineattach" : "attach"); boolean editable = isFileEditableInDocEditor(pname); sout += "{iddata:'" + iddata + "',value1:'" + (i + idattach) + "',value2:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(pname)) + "',value3:" + rsize + ",value4:" + (imgname == null ? "null" : "'" + StringEscapeUtils.escapeEcmaScript(imgname) + "'") + ", editable: " + editable + " },\n"; } if (!mcache.isDrafts() && !mcache.isSent() && !mcache.isSpam() && !mcache.isTrash() && !mcache.isArchive()) { if (vheader != null && vheader[0] != null && !wasseen) { sout += "{iddata:'receipt',value1:'" + us.getReadReceiptConfirmation() + "',value2:'" + StringEscapeUtils.escapeEcmaScript(vheader[0]) + "',value3:0},\n"; } } String h = getSingleHeaderValue(m, "Sonicle-send-scheduled"); if (h != null && h.equals("true")) { java.util.Calendar scal = parseScheduleHeader(getSingleHeaderValue(m, "Sonicle-send-date"), getSingleHeaderValue(m, "Sonicle-send-time")); if (scal != null) { java.util.Date sd = scal.getTime(); String sdate = df.format(sd).replaceAll("\\.", ":"); sout += "{iddata:'scheddate',value1:'" + StringEscapeUtils.escapeEcmaScript(sdate) + "',value2:'',value3:0},\n"; } } if (ir != null) { /* ICalendarManager calMgr = (ICalendarManager)WT.getServiceManager("com.sonicle.webtop.calendar",environment.getProfileId()); if (calMgr != null) { if (ir.getMethod().equals("REPLY")) { calMgr.updateEventFromICalReply(ir.getCalendar()); //TODO: gestire lato client una notifica di avvenuto aggiornamento } else { Event evt = calMgr..getEvent(GetEventScope.PERSONAL_AND_INCOMING, false, ir.getUID()) if (evt != null) { UserProfileId pid = getEnv().getProfileId(); UserProfile.Data ud = WT.getUserData(pid); boolean iAmOrganizer = StringUtils.equalsIgnoreCase(evt.getOrganizerAddress(), ud.getEmailAddress()); boolean iAmOwner = pid.equals(calMgr.getCalendarOwner(evt.getCalendarId())); if (!iAmOrganizer && !iAmOwner) { //TODO: gestire lato client l'aggiornamento: Accetta/Rifiuta, Aggiorna e20 dopo update/request } } } } */ ICalendarManager cm = (ICalendarManager) WT.getServiceManager("com.sonicle.webtop.calendar", true, environment.getProfileId()); if (cm != null) { int eid = -1; //Event ev=cm.getEventByScope(EventScope.PERSONAL_AND_INCOMING, ir.getUID()); Event ev = null; if (ir.getMethod().equals("REPLY")) { // Previous impl. forced (forceOriginal == true) ev = cm.getEvent(GetEventScope.PERSONAL_AND_INCOMING, ir.getUID()); } else { ev = cm.getEvent(GetEventScope.PERSONAL_AND_INCOMING, ir.getUID()); } UserProfileId pid = getEnv().getProfileId(); UserProfile.Data ud = WT.getUserData(pid); if (ev != null) { InternetAddress organizer = InternetAddressUtils.toInternetAddress(ev.getOrganizer()); boolean iAmOwner = pid.equals(cm.getCalendarOwner(ev.getCalendarId())); boolean iAmOrganizer = (organizer != null) && StringUtils.equalsIgnoreCase(organizer.getAddress(), ud.getEmailAddress()); //TODO: in reply controllo se mail combacia con quella dell'attendee che risponde... //TODO: rimuovere controllo su data? dovrebbe sempre aggiornare? if (iAmOwner || iAmOrganizer) { eid = 0; //TODO: troviamo un modo per capire se la risposta si riverisce all'ultima versione dell'evento? Nuovo campo timestamp? /* DateTime dtEvt = ev.getRevisionTimestamp().withMillisOfSecond(0).withZone(DateTimeZone.UTC); DateTime dtICal = ICal4jUtils.fromICal4jDate(ir.getLastModified(), ICal4jUtils.getTimeZone(DateTimeZone.UTC)); if (dtICal.isAfter(dtEvt)) { eid = 0; } else { eid = ev.getEventId(); } */ } } sout += "{iddata:'ical',value1:'" + ir.getMethod() + "',value2:'" + ir.getUID() + "',value3:'" + eid + "'},\n"; } } sout += "{iddata:'date',value1:'" + StringEscapeUtils.escapeEcmaScript(date) + "',value2:'',value3:0},\n"; sout += "{iddata:'subject',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(subject)) + "',value2:'',value3:0},\n"; sout += "{iddata:'messageid',value1:'" + StringEscapeUtils.escapeEcmaScript(messageid) + "',value2:'',value3:0}\n"; if (providername == null && !mcache.isSpecial()) { mcache.refreshUnreads(); } long millis = System.currentTimeMillis(); sout += "\n],\n"; String svtags = getJSTagsArray(m.getFlags()); if (svtags != null) sout += "tags: " + svtags + ",\n"; if (isPECView) { sout += "pec: true,\n"; } sout += "total:" + recs + ",\nmillis:" + millis + "\n}\n"; out.println(sout); if (im != null) im.setPeek(false); // if (!wasopen) folder.close(false); } catch (Exception exc) { Service.logger.error("Exception", exc); } }