List of usage examples for javax.mail Part getFileName
public String getFileName() throws MessagingException;
From source file:org.pentaho.di.job.entries.getpop.MailConnection.java
private void handlePart(String foldername, Part part, Pattern pattern) throws KettleException { try {//from w w w .j a v a2 s. c o m String disposition = part.getDisposition(); // The RFC2183 doesn't REQUIRE Content-Disposition header field so we'll create one to // fake out the code below. if (disposition == null || disposition.length() < 1) { disposition = Part.ATTACHMENT; } if (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE)) { String MimeText = null; try { MimeText = MimeUtility.decodeText(part.getFileName()); } catch (Exception e) { // Ignore errors } if (MimeText != null) { String filename = MimeUtility.decodeText(part.getFileName()); if (isWildcardMatch(filename, pattern)) { // Save file saveFile(foldername, filename, part.getInputStream()); updateSavedAttachedFilesCounter(); if (log.isDetailed()) { log.logDetailed(BaseMessages.getString(PKG, "JobGetMailsFromPOP.AttachedFileSaved", filename, "" + getMessage().getMessageNumber(), foldername)); } } } } } catch (Exception e) { throw new KettleException(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 a 2 s .c o m */ 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: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: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 . j a va2 s . com * * @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:com.flexoodb.common.FlexUtils.java
/** * method to obtain a FileContainer containing the file wrapped in a mimemessage. * * @param data the mimemessage in a byte array. * @return a FileContainer containing the file. *///from ww w.j a v a 2 s.c o m static public FileContainer extractFileFromMimeMessage(byte[] data) throws Exception { FileContainer fc = null; MimeMessage message = new MimeMessage(null, new ByteArrayInputStream(data)); Object content = message.getContent(); if (content instanceof Multipart) { Multipart multipart = (Multipart) content; for (int i = 0, n = multipart.getCount(); i < n; i++) { Part part = multipart.getBodyPart(i); String disposition = part.getDisposition(); if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE)))) { if (part.getFileName() != null) { fc = new FileContainer(part.getFileName(), part.getFileName(), getBytesFromInputStream(part.getInputStream())); break; } } } } return fc; }
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//w w w . ja va 2 s . c o m * // 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.manifoldcf.crawler.connectors.email.EmailConnector.java
/** Process a set of documents. * This is the method that should cause each document to be fetched, processed, and the results either added * to the queue of documents for the current job, and/or entered into the incremental ingestion manager. * The document specification allows this class to filter what is done based on the job. * The connector will be connected before this method can be called. *@param documentIdentifiers is the set of document identifiers to process. *@param statuses are the currently-stored document versions for each document in the set of document identifiers * passed in above.//from w ww . j av a 2 s .co m *@param activities is the interface this method should use to queue up new document references * and ingest documents. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one. */ @Override public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec, IProcessActivity activities, int jobMode, boolean usesDefaultAuthority) throws ManifoldCFException, ServiceInterruption { List<String> requiredMetadata = new ArrayList<String>(); for (int i = 0; i < spec.getChildCount(); i++) { SpecificationNode sn = spec.getChild(i); if (sn.getType().equals(EmailConfig.NODE_METADATA)) { String metadataAttribute = sn.getAttributeValue(EmailConfig.ATTRIBUTE_NAME); requiredMetadata.add(metadataAttribute); } } // Keep a cached set of open folders Map<String, Folder> openFolders = new HashMap<String, Folder>(); try { for (String documentIdentifier : documentIdentifiers) { String versionString = "_" + urlTemplate; // NOT empty; we need to make ManifoldCF understand that this is a document that never will change. // Check if we need to index if (!activities.checkDocumentNeedsReindexing(documentIdentifier, versionString)) continue; String compositeID = documentIdentifier; String version = versionString; String folderName = extractFolderNameFromDocumentIdentifier(compositeID); String id = extractEmailIDFromDocumentIdentifier(compositeID); String errorCode = null; String errorDesc = null; Long fileLengthLong = null; long startTime = System.currentTimeMillis(); try { try { Folder folder = openFolders.get(folderName); if (folder == null) { getSession(); OpenFolderThread oft = new OpenFolderThread(session, folderName); oft.start(); folder = oft.finishUp(); openFolders.put(folderName, folder); } if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Email: Processing document identifier '" + compositeID + "'"); SearchTerm messageIDTerm = new MessageIDTerm(id); getSession(); SearchMessagesThread smt = new SearchMessagesThread(session, folder, messageIDTerm); smt.start(); Message[] message = smt.finishUp(); String msgURL = makeDocumentURI(urlTemplate, folderName, id); Message msg = null; for (Message msg2 : message) { msg = msg2; } if (msg == null) { // email was not found activities.deleteDocument(id); continue; } if (!activities.checkURLIndexable(msgURL)) { errorCode = activities.EXCLUDED_URL; errorDesc = "Excluded because of URL ('" + msgURL + "')"; activities.noDocument(id, version); continue; } long fileLength = msg.getSize(); if (!activities.checkLengthIndexable(fileLength)) { errorCode = activities.EXCLUDED_LENGTH; errorDesc = "Excluded because of length (" + fileLength + ")"; activities.noDocument(id, version); continue; } Date sentDate = msg.getSentDate(); if (!activities.checkDateIndexable(sentDate)) { errorCode = activities.EXCLUDED_DATE; errorDesc = "Excluded because of date (" + sentDate + ")"; activities.noDocument(id, version); continue; } String mimeType = "text/plain"; if (!activities.checkMimeTypeIndexable(mimeType)) { errorCode = activities.EXCLUDED_DATE; errorDesc = "Excluded because of mime type ('" + mimeType + "')"; activities.noDocument(id, version); continue; } RepositoryDocument rd = new RepositoryDocument(); rd.setFileName(msg.getFileName()); rd.setMimeType(mimeType); rd.setCreatedDate(sentDate); rd.setModifiedDate(sentDate); String subject = StringUtils.EMPTY; for (String metadata : requiredMetadata) { if (metadata.toLowerCase().equals(EmailConfig.EMAIL_TO)) { Address[] to = msg.getRecipients(Message.RecipientType.TO); String[] toStr = new String[to.length]; int j = 0; for (Address address : to) { toStr[j] = address.toString(); } rd.addField(EmailConfig.EMAIL_TO, toStr); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_FROM)) { Address[] from = msg.getFrom(); String[] fromStr = new String[from.length]; int j = 0; for (Address address : from) { fromStr[j] = address.toString(); } rd.addField(EmailConfig.EMAIL_TO, fromStr); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_SUBJECT)) { subject = msg.getSubject(); rd.addField(EmailConfig.EMAIL_SUBJECT, subject); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_BODY)) { Multipart mp = (Multipart) msg.getContent(); for (int k = 0, n = mp.getCount(); k < n; k++) { Part part = mp.getBodyPart(k); String disposition = part.getDisposition(); if ((disposition == null)) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType(EmailConfig.MIMETYPE_TEXT_PLAIN)) { rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString()); } else if (mbp.isMimeType(EmailConfig.MIMETYPE_HTML)) { rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString()); //handle html accordingly. Returns content with html tags } } } } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_DATE)) { rd.addField(EmailConfig.EMAIL_DATE, sentDate.toString()); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_ENCODING)) { Multipart mp = (Multipart) msg.getContent(); if (mp != null) { String[] encoding = new String[mp.getCount()]; for (int k = 0, n = mp.getCount(); k < n; k++) { Part part = mp.getBodyPart(k); String disposition = part.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) { encoding[k] = part.getFileName().split("\\?")[1]; } } rd.addField(EmailConfig.ENCODING_FIELD, encoding); } } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_MIMETYPE)) { Multipart mp = (Multipart) msg.getContent(); String[] MIMEType = new String[mp.getCount()]; for (int k = 0, n = mp.getCount(); k < n; k++) { Part part = mp.getBodyPart(k); String disposition = part.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) { MIMEType[k] = part.getContentType(); } } rd.addField(EmailConfig.MIMETYPE_FIELD, MIMEType); } } InputStream is = msg.getInputStream(); try { rd.setBinary(is, fileLength); activities.ingestDocumentWithException(id, version, msgURL, rd); errorCode = "OK"; fileLengthLong = new Long(fileLength); } finally { is.close(); } } catch (InterruptedException e) { throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED); } catch (MessagingException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleMessagingException(e, "processing email"); } catch (IOException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleIOException(e, "processing email"); throw new ManifoldCFException(e.getMessage(), e); } } catch (ManifoldCFException e) { if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) errorCode = null; throw e; } finally { if (errorCode != null) activities.recordActivity(new Long(startTime), EmailConfig.ACTIVITY_FETCH, fileLengthLong, documentIdentifier, errorCode, errorDesc, null); } } } finally { for (Folder f : openFolders.values()) { try { CloseFolderThread cft = new CloseFolderThread(session, f); cft.start(); cft.finishUp(); } catch (InterruptedException e) { throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED); } catch (MessagingException e) { handleMessagingException(e, "closing folders"); } } } }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Writes a passed payload part to the passed message object. *//*from ww w .ja v a 2 s. 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:com.sonicle.webtop.mail.Service.java
public String getPartName(Part p) throws MessagingException { String pname = p.getFileName(); // TODO: Remove code below if already included in JavaMail impl. if (pname == null) { String hctypes[] = p.getHeader("Content-Type"); if (hctypes == null || hctypes.length == 0) { return null; }//from w w w .j av a 2 s . c o m String hctype = hctypes[0]; int ix = hctype.indexOf("name="); if (ix >= 0) { int sx = ix + 5; int ex = hctype.indexOf(";", sx); if (ex >= 0) { pname = hctype.substring(sx, ex); } else { pname = hctype.substring(sx); } pname = pname.trim(); int xx = pname.length() - 1; if (pname.charAt(0) == '"' && pname.charAt(xx) == '"') { pname = pname.substring(1, xx); } } if (pname == null) { return null; } logger.warn("Code in getPartName is still used. Please review it!"); try { pname = MimeUtility.decodeText(pname); } catch (UnsupportedEncodingException ex) { Service.logger.error("Exception", ex); } } return pname; }
From source file:com.sonicle.webtop.mail.Service.java
public void processSaveFileToCloud(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { try {//from w w w.j a v a 2 s . co m MailAccount account = getAccount(request); String path = ServletUtils.getStringParameter(request, "path", true); String fileId = ServletUtils.getStringParameter(request, "fileId", true); int storeId = ServletUtils.getIntParameter(request, "storeId", true); String folder = ServletUtils.getStringParameter(request, "folder", true); int idAttach = ServletUtils.getIntParameter(request, "idAttach", true); int idMessage = ServletUtils.getIntParameter(request, "idMessage", true); account.checkStoreConnected(); FolderCache mcache = account.getFolderCache(folder); Message m = mcache.getMessage(idMessage); HTMLMailData mailData = mcache.getMailData((MimeMessage) m); Part part = mailData.getAttachmentPart(idAttach); String fileName = part.getFileName(); InputStream is = part.getInputStream(); vfsmanager.addStoreFileFromStream(storeId, path, fileName, is); MapItem data = new MapItem(); data.add("success", true); new JsonResult(data).printTo(out); } catch (Exception ex) { Service.logger.error("Exception", ex); new JsonResult(false, ex.getMessage()).printTo(out); } }