List of usage examples for javax.mail Part getFileName
public String getFileName() throws MessagingException;
From source file:org.alfresco.email.server.impl.subetha.SubethaEmailMessage.java
/** * Method extracts file name from a message part for saving its as aa attachment. If the file name can't be extracted, it will be generated based on defaultPrefix parameter. * /*from w w w . j av a2s . c o m*/ * @param defaultPrefix This prefix fill be used for generating file name. * @param messagePart A part of message * @return File name. * @throws MessagingException */ private String getPartFileName(String defaultPrefix, Part messagePart) throws MessagingException { String fileName = messagePart.getFileName(); if (fileName != null) { try { fileName = MimeUtility.decodeText(fileName); } catch (UnsupportedEncodingException ex) { // Nothing to do :) } } else { fileName = defaultPrefix; if (messagePart.isMimeType(MIME_PLAIN_TEXT)) fileName += ".txt"; else if (messagePart.isMimeType(MIME_HTML_TEXT)) fileName += ".html"; else if (messagePart.isMimeType(MIME_XML_TEXT)) fileName += ".xml"; else if (messagePart.isMimeType(MIME_IMAGE)) fileName += ".gif"; } return fileName; }
From source file:org.alfresco.repo.imap.AttachmentsExtractor.java
/** * Create an attachment given a mime part * /*ww w.j ava 2 s.c o m*/ * @param messageFile the file containing the message * @param attachmentsFolderRef where to put the attachment * @param part the mime part * @throws MessagingException * @throws IOException */ private void createAttachment(NodeRef messageFile, NodeRef attachmentsFolderRef, Part part) throws MessagingException, IOException { String fileName = part.getFileName(); if (fileName == null || fileName.isEmpty()) { fileName = "unnamed"; } try { fileName = MimeUtility.decodeText(fileName); } catch (UnsupportedEncodingException e) { if (logger.isWarnEnabled()) { logger.warn("Cannot decode file name '" + fileName + "'", e); } } ContentType contentType = new ContentType(part.getContentType()); if (contentType.getBaseType().equalsIgnoreCase("application/ms-tnef")) { // The content is TNEF HMEFMessage hmef = new HMEFMessage(part.getInputStream()); // hmef.getBody(); List<org.apache.poi.hmef.Attachment> attachments = hmef.getAttachments(); for (org.apache.poi.hmef.Attachment attachment : attachments) { String subName = attachment.getLongFilename(); NodeRef attachmentNode = fileFolderService.searchSimple(attachmentsFolderRef, subName); if (attachmentNode == null) { /* * If the node with the given name does not already exist Create the content node to contain the attachment */ FileInfo createdFile = fileFolderService.create(attachmentsFolderRef, subName, ContentModel.TYPE_CONTENT); attachmentNode = createdFile.getNodeRef(); serviceRegistry.getNodeService().createAssociation(messageFile, attachmentNode, ImapModel.ASSOC_IMAP_ATTACHMENT); byte[] bytes = attachment.getContents(); ContentWriter writer = fileFolderService.getWriter(attachmentNode); // TODO ENCODING - attachment.getAttribute(TNEFProperty.); String extension = attachment.getExtension(); String mimetype = mimetypeService.getMimetype(extension); if (mimetype != null) { writer.setMimetype(mimetype); } OutputStream os = writer.getContentOutputStream(); ByteArrayInputStream is = new ByteArrayInputStream(bytes); FileCopyUtils.copy(is, os); } } } else { // not TNEF NodeRef attachmentFile = fileFolderService.searchSimple(attachmentsFolderRef, fileName); // The one possible behaviour /* * if (result.size() > 0) { for (FileInfo fi : result) { fileFolderService.delete(fi.getNodeRef()); } } */ // And another one behaviour which will overwrite the content of the existing file. It is performance preferable. if (attachmentFile == null) { FileInfo createdFile = fileFolderService.create(attachmentsFolderRef, fileName, ContentModel.TYPE_CONTENT); nodeService.createAssociation(messageFile, createdFile.getNodeRef(), ImapModel.ASSOC_IMAP_ATTACHMENT); attachmentFile = createdFile.getNodeRef(); } else { String newFileName = imapService.generateUniqueFilename(attachmentsFolderRef, fileName); FileInfo createdFile = fileFolderService.create(attachmentsFolderRef, newFileName, ContentModel.TYPE_CONTENT); nodeService.createAssociation(messageFile, createdFile.getNodeRef(), ImapModel.ASSOC_IMAP_ATTACHMENT); attachmentFile = createdFile.getNodeRef(); } nodeService.setProperty(attachmentFile, ContentModel.PROP_DESCRIPTION, nodeService.getProperty(messageFile, ContentModel.PROP_NAME)); ContentWriter writer = fileFolderService.getWriter(attachmentFile); writer.setMimetype(contentType.getBaseType()); OutputStream os = writer.getContentOutputStream(); FileCopyUtils.copy(part.getInputStream(), os); } }
From source file:org.xmlactions.email.EMailParser.java
private void addPart(Part part) throws IOException, MessagingException, DocumentException { String contentType = part.getContentType(); boolean isAttachment; if (part.getFileName() != null) { isAttachment = true;/*from w w w. j a va 2s . co m*/ } else { isAttachment = false; } log.debug("isAttachment:" + isAttachment + " contentType:" + contentType); if (isAttachment == true) { } else { // Check if plain if (contentType.toLowerCase().indexOf("text/plain") >= 0) { log.debug("process text/plain"); setIgnoreHTML(true); // if we get any text/plain for body } else if (isIgnoreHTML() == false && contentType.toLowerCase().indexOf("text/html") >= 0) { // log.debug("skipping text/html"); log.debug("process text/html"); InputStream is = convertHTMLToText(part.getInputStream()); try { } finally { IOUtils.closeQuietly(is); } } else { log.debug("ignoring part [" + contentType + "]"); } } }
From source file:org.xmlactions.email.EMailParser.java
private void showPart(Part part) throws IOException, MessagingException { log.info("\n\n\nshowPart ==>>"); log.info("part.toString():" + part.toString()); log.info("part.getContent():" + (part.getFileName() == null ? part.getContent().toString() : "Attachment")); log.info("part.getContentType():" + part.getContentType()); log.info("part.getFilename():" + part.getFileName()); log.info("part.isAttachment:" + part.getFileName()); log.info("part.isMessage:" + (part.getContent() instanceof Message)); Object obj = part.getContent(); if (obj instanceof Multipart) { log.info("MultiPart"); Multipart mmp = (Multipart) obj; for (int i = 0; i < mmp.getCount(); i++) { Part bodyPart = mmp.getBodyPart(i); showPart(bodyPart);//from w ww .j a v a 2 s . com } } else if (obj instanceof Part) { showPart((Part) obj); } else { log.info("=== Add Part ==="); log.info((String) (part.getFileName() != null ? "isAttachment" : part.getContent())); // log.info("not recognised class:" + obj.getClass().getName() + // "\n" + obj); } log.info("<<== showPart"); }
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 va 2s . c om 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; }
From source file:org.xmlactions.email.EMailParser.java
private void handlePart(Part part) throws MessagingException, IOException, DocumentException { log.debug("\n\n\nhandlePart ==>>"); log.debug("part.toString():" + part.toString()); log.debug(/*from w ww. j a v a2s. c om*/ "part.getContent():" + (part.getFileName() == null ? part.getContent().toString() : "Attachment")); log.debug("part.getContentType():" + part.getContentType()); log.debug("part.getFilename():" + part.getFileName()); log.debug("part.isAttachment:" + part.getFileName()); log.debug("part.isMessage:" + (part.getContent() instanceof Message)); Object obj = part.getContent(); if (obj instanceof Multipart) { Multipart mmp = (Multipart) obj; for (int i = 0; i < mmp.getCount(); i++) { Part bodyPart = mmp.getBodyPart(i); if (bodyPart instanceof Message) { setFirstMessageProcessed(true);// need to mark this when we // get a forwarded message // so we don't look for case // numbers in forwarded // emails. } handlePart(bodyPart); } } else if (obj instanceof Part) { if (obj instanceof Message) { setFirstMessageProcessed(true);// need to mark this when we get // a forwarded message so we // don't look for case numbers // in forwarded emails. } handlePart((Part) obj); } else { if (part instanceof MimeBodyPart) { MimeBodyPart p = (MimeBodyPart) part; Enumeration enumeration = p.getAllHeaders(); while (enumeration.hasMoreElements()) { Object e = enumeration.nextElement(); if (e == null) e = null; } Object content = p.getContent(); enumeration = p.getAllHeaderLines(); while (enumeration.hasMoreElements()) { Object e = enumeration.nextElement(); if (e == null) e = null; } DataHandler dh = p.getDataHandler(); if (dh == null) dh = null; } addPart(part); log.debug("=== Add Part ==="); log.debug((String) (part.getFileName() != null ? "isAttachment" : part.getContent())); // log.info("not recognised class:" + obj.getClass().getName() + // "\n" + obj); } log.debug("<<== handlePart"); }
From source file:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java
private boolean hasFileName(Part part) throws MessagingException { return (part.getFileName() != null && !part.getFileName().trim().isEmpty()); }
From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java
private void addEmailAttachmentsToJob(final DepositEmailConfiguration depositEmailConfiguration, final MimeMessage mimeMessage, final MultiFilesJob job) throws MessagingException, IOException, FileNotFoundException { final String jobConfigurationFileName = depositEmailConfiguration.getJobConfigurationFileName(); if (StringUtils.isNotBlank(jobConfigurationFileName)) { final File jobConfigurationFile = getJobConfigurationFile( depositEmailConfiguration.getApplicationName(), jobConfigurationFileName); job.addFile(Constants.MULTIPLE_FILES_JOB_CONFIGURATION, new FileInputStream(jobConfigurationFile)); }/*from w w w .j a v a 2 s . co m*/ final Object content = mimeMessage.getContent(); Validate.isTrue(content instanceof Multipart, "only multipart emails can be processed"); final Multipart multipart = (Multipart) content; for (int i = 0, n = multipart.getCount(); i < n; i++) { final Part part = multipart.getBodyPart(i); final String disposition = part.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) { final String name = part.getFileName(); final String contentType = StringUtils.substringBefore(part.getContentType(), ";"); MultiFilesJob.addDataToJob(contentType, name, part.getInputStream(), job); } } }
From source file:org.apache.james.transport.mailets.StripAttachment.java
/** * Saves the content of the part to a file in the given directoy, using the * name of the part. If a file with that name already exists, it will * /*w w w . java 2s. c o m*/ * @param part * The MIME part to save. * @return * @throws Exception */ private String saveAttachmentToFile(Part part, String fileName) throws Exception { BufferedOutputStream os = null; InputStream is = null; File f = null; try { if (fileName == null) fileName = part.getFileName(); int pos = -1; if (fileName != null) { pos = fileName.lastIndexOf("."); } String prefix = pos > 0 ? (fileName.substring(0, pos)) : fileName; String suffix = pos > 0 ? (fileName.substring(pos)) : ".bin"; while (prefix.length() < 3) prefix += "_"; if (suffix.length() == 0) suffix = ".bin"; f = File.createTempFile(prefix, suffix, new File(directoryName)); log("saving content of " + f.getName() + "..."); os = new BufferedOutputStream(new FileOutputStream(f)); is = part.getInputStream(); if (!(is instanceof BufferedInputStream)) { is = new BufferedInputStream(is); } int c; while ((c = is.read()) != -1) { os.write(c); } return f.getName(); } catch (Exception e) { log("Error while saving contents of [" + (f != null ? f.getName() : (part != null ? part.getFileName() : "NULL")) + "].", e); throw e; } finally { is.close(); os.close(); } }
From source file:org.xwiki.contrib.mail.internal.JavamailMessageParser.java
/** * Recursively extracts content of an email. Every Part that has a file name, or is neither multipart, plain text or * html, is considered an attachment.//from w ww . ja v a 2 s . co m * * @param part * @return * @throws MessagingException * @throws UnsupportedEncodingException * @throws IOException */ public MailContent extractPartsContent(Part part) throws MessagingException, IOException { MailContent mailContent = new MailContent(); String contentType = part.getContentType().toLowerCase(); if (!StringUtils.isBlank(part.getFileName()) || (!contentType.startsWith("multipart/") && !part.isMimeType("text/plain") && !part.isMimeType("text/html"))) { mailContent.addAttachment((MimeBodyPart) part); } else if (part.isMimeType("text/plain")) { logger.debug("Extracting part PLAIN TEXT"); mailContent.appendText(MimeUtility.decodeText((String) part.getContent())); } else if (part.isMimeType("text/html")) { logger.debug("Extracting part HTML"); mailContent.appendHtml(MimeUtility.decodeText((String) part.getContent())); } else if (part.isMimeType("message/rfc822")) { logger.debug("Extracting part message/rfc822"); Message innerMessage = (Message) part.getContent(); mailContent.addAttachedMail(innerMessage); // FIXME attached mails should be loaded previously to their container } else if (contentType.startsWith("multipart/")) { logger.debug("Extracting MULTIPART"); Multipart multipart = (Multipart) part.getContent(); if (contentType.startsWith("multipart/signed")) { // Signed multiparts contain 2 parts: first is the content, second is the control information // We just ignore the control information logger.debug("Extracting SIGNED MULTIPART"); mailContent.append(extractPartsContent(multipart.getBodyPart(0))); } else if (part.isMimeType("multipart/related") || part.isMimeType("multipart/mixed") || part.isMimeType("multipart/alternative")) { logger.debug("Extracting multipart / related or mixed or alternative"); // FIXME multipart/alternative should be treated differently than other parts, though the same treatment // should be ok most of the time // (multipart/alternative is usually one part text/plain and the alternative text/html, so as text and // html // are always considered alternates by this algorithm, it's ok) int i = 0; int mcount = multipart.getCount(); while (i < mcount) { logger.debug("Adding MULTIPART #{}", i); try { final MailContent innerMailContent = extractPartsContent(multipart.getBodyPart(i)); mailContent.append(innerMailContent); } catch (Exception e) { logger.warn("Could not add MULTIPART #{} because of {}", i, ExceptionUtils.getRootCause(e)); } i++; } } else { logger.info("Multipart subtype {} not managed", contentType.substring(0, contentType.indexOf(' '))); } } else { logger.info("Message Type {} not managed", contentType.substring(0, contentType.indexOf('/'))); } return mailContent; }