List of usage examples for javax.mail Part getContentType
public String getContentType() throws MessagingException;
From source file:org.alfresco.repo.content.transform.EMLParser.java
/** * Gets the charset from content type.//from ww w. j a v a 2 s . c o m * * @param part * the part to process * @return the charset if found or UTF-8 as default */ private String getCharset(Part part) { String charset = UTF_8; String contentType = null; try { contentType = part.getContentType(); int indexOf = contentType.indexOf("charset="); if (indexOf != -1) { charset = (contentType.substring(indexOf) + ";").replaceAll("charset=\"?", "") .replaceAll("\"?;(\\s*.*)", ""); } Charset.forName(charset); } catch (Exception e) { logger.error("Error processing content type: " + contentType, e); charset = UTF_8; } return charset; }
From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java
@Override public List<GmailAttachment> getAttachements() { List<GmailAttachment> result = new ArrayList<GmailAttachment>(); try {/*from www . j ava 2s.co m*/ Object content = this.source.getContent(); if (content instanceof Multipart) { Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { Part bodyPart = multipart.getBodyPart(i); if (bodyPart.getDisposition() != null) { if (bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) { result.add(new GmailAttachment(i, bodyPart.getFileName(), bodyPart.getContentType(), bodyPart.getInputStream())); } } } } } catch (Exception e) { throw new GmailException("Failed to get attachements", e); } return result; }
From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java
@Override public GmailAttachment getAttachment(int partIndex) { GmailAttachment result = null;/*from w w w . ja va2 s. c om*/ try { Object content = this.source.getContent(); if (content instanceof Multipart) { Multipart multipart = (Multipart) content; Part bodyPart = multipart.getBodyPart(partIndex); if (bodyPart.getDisposition() != null) { if (bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) { result = new GmailAttachment(partIndex, bodyPart.getFileName(), bodyPart.getContentType(), bodyPart.getInputStream()); } } } else { throw new GmailException("Failed to get attachement with partIndex :" + partIndex); } } catch (Exception e) { throw new GmailException("Failed to get attachement with partIndex :" + partIndex, e); } return result; }
From source file:org.sourceforge.net.javamail4ews.transport.EwsTransport.java
private MessageBody createBodyFromPart(EmailMessage msg, Part part, boolean treatAsAttachement) throws MessagingException, IOException, ServiceLocalException { MessageBody mb = new MessageBody(); if (part.isMimeType(TEXT_PLAIN)) { String s = (String) part.getContent(); mb.setBodyType(BodyType.Text); mb.setText(s);//from w ww . j a va 2 s . co m } else if (part.isMimeType(TEXT_STAR)) { logger.debug("mime-type is '" + part.getContentType() + "' handling as " + TEXT_HTML); String s = (String) part.getContent(); mb.setBodyType(BodyType.HTML); mb.setText(s); } else if (part.isMimeType(MULTIPART_ALTERNATIVE) && !treatAsAttachement) { logger.debug("mime-type is '" + part.getContentType() + "'"); Multipart mp = (Multipart) part.getContent(); String text = ""; for (int i = 0; i < mp.getCount(); i++) { Part p = mp.getBodyPart(i); if (p.isMimeType(TEXT_HTML)) { text += p.getContent(); } } mb.setText(text); mb.setBodyType(BodyType.HTML); if (!treatAsAttachement) createBodyFromPart(msg, part, true); } else if (part.isMimeType(MULTIPART_STAR) && !part.isMimeType(MULTIPART_ALTERNATIVE)) { logger.debug("mime-type is '" + part.getContentType() + "'"); Multipart mp = (Multipart) part.getContent(); int start = 0; if (!treatAsAttachement) { mb = createBodyFromPart(msg, mp.getBodyPart(start), false); start++; } for (int i = start; i < mp.getCount(); i++) { BodyPart lBodyPart = mp.getBodyPart(i); byte[] lContentBytes = bodyPart2ByteArray(lBodyPart); FileAttachment lNewAttachment; String lContentId = getFirstHeaderValue(lBodyPart, "Content-ID"); if (lContentId != null) { lNewAttachment = msg.getAttachments().addFileAttachment(lContentId, lContentBytes); lNewAttachment.setContentId(lContentId); lNewAttachment.setIsInline(true); logger.debug("Attached {} bytes as content {}", lContentBytes.length, lContentId); } else { String fileName = lBodyPart.getFileName(); fileName = (fileName == null ? "" + i : fileName); lNewAttachment = msg.getAttachments().addFileAttachment(fileName, lContentBytes); lNewAttachment.setIsInline(false); lNewAttachment.setContentType(lBodyPart.getContentType()); logger.debug("Attached {} bytes as file {}", lContentBytes.length, fileName); logger.debug("content type is {} ", lBodyPart.getContentType()); } lNewAttachment.setIsContactPhoto(false); } } return mb; }
From source file:org.zilverline.core.IMAPCollection.java
/** * Index a part./*from ww w . j av a 2 s . c om*/ */ private void indexPart(final Document doc, final Part p) throws MessagingException, IOException { int size = p.getSize(); String ct = p.getContentType(); String cd = p.getDescription(); log.debug("IndexContent, type: " + ct + ", description: " + cd); Object content = null; if (ct != null) { doc.add(Field.Keyword(F_CT, ct)); } doc.add(Field.Keyword("type", "MAIL")); if (cd != null) { doc.add(Field.Keyword(F_CD, cd)); } if (ct != null && ct.toLowerCase().startsWith("image/")) { // no point for now but maybe in the future we see if any forms such as jpegs have some strings return; } try { // get content object, indirectly calls into JAF which decodes based on MIME type and char content = p.getContent(); } catch (IOException ioe) { log.warn("OUCH decoding attachment, p=" + p, ioe); doc.add(Field.Text(F_CONTENTS, new InputStreamReader(p.getInputStream()))); return; } if (content instanceof MimeMultipart) { int n = ((MimeMultipart) content).getCount(); for (int i = 0; i < n; i++) { BodyPart bp = ((MimeMultipart) content).getBodyPart(i); // same thing ends up happening regardless, if/else left it to show structure indexPart(doc, bp); } } else if (content instanceof MimePart) { indexPart(doc, (MimePart) content); } else if (content instanceof Part) { indexPart(doc, (Part) content); } else if (content instanceof String) { indexString(doc, (String) content, ct); } else if (content instanceof InputStream) { indexStream(doc, (InputStream) content, ct); } else { log.error("***** Strange content: " + content + "/" + content.getClass() + " ct=" + ct + " cd=" + cd); } }
From source file:org.alfresco.repo.imap.AttachmentsExtractor.java
/** * Create an attachment given a mime part * //from w w w. ja va 2s.co 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:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java
private void extractBody(Part Mess, cfArrayData AD, String attachURI, String attachDIR) throws Exception { if (Mess.isMimeType("multipart/*")) { Multipart mp = (Multipart) Mess.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) extractBody(mp.getBodyPart(i), AD, attachURI, attachDIR); } else {// www . j a v a2 s . c o m cfStructData sd = new cfStructData(); String tmp = Mess.getContentType(); if (tmp.indexOf(";") != -1) tmp = tmp.substring(0, tmp.indexOf(";")); sd.setData("mimetype", new cfStringData(tmp)); String filename = getFilename(Mess); String dispos = getDisposition(Mess); MimeType messtype = new MimeType(tmp); // Note that we can't use Mess.isMimeType() here due to bug #2080 if ((dispos == null || dispos.equalsIgnoreCase(Part.INLINE)) && messtype.match("text/*")) { Object content; String contentType = Mess.getContentType().toLowerCase(); // support aliases of UTF-7 - UTF7, UNICODE-1-1-UTF-7, csUnicode11UTF7, UNICODE-2-0-UTF-7 if (contentType.indexOf("utf-7") != -1 || contentType.indexOf("utf7") != -1) { InputStream ins = Mess.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(ins, bos); content = new String(UTF7Converter.convert(bos.toByteArray())); } else { try { content = Mess.getContent(); } catch (UnsupportedEncodingException e) { content = Mess.getInputStream(); } catch (IOException ioe) { // This will happen on BD/Java when the attachment has no content // NOTE: this is the fix for bug NA#3198. content = ""; } } if (content instanceof InputStream) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy((InputStream) content, bos); sd.setData("content", new cfStringData(new String(bos.toByteArray()))); } else { sd.setData("content", new cfStringData(content.toString())); } sd.setData("file", cfBooleanData.FALSE); sd.setData("filename", new cfStringData(filename == null ? "" : filename)); } else if (attachDIR != null) { sd.setData("content", new cfStringData("")); if (filename == null || filename.length() == 0) filename = "unknownfile"; filename = getAttachedFilename(attachDIR, filename); //--[ An attachment, save it out to disk try { BufferedInputStream in = new BufferedInputStream(Mess.getInputStream()); BufferedOutputStream out = new BufferedOutputStream( cfEngine.thisPlatform.getFileIO().getFileOutputStream(new File(attachDIR + filename))); IOUtils.copy(in, out); out.flush(); out.close(); in.close(); sd.setData("file", cfBooleanData.TRUE); sd.setData("filename", new cfStringData(filename)); if (attachURI.charAt(attachURI.length() - 1) != '/') sd.setData("url", new cfStringData(attachURI + '/' + filename)); else sd.setData("url", new cfStringData(attachURI + filename)); sd.setData("size", new cfNumberData((int) new File(attachDIR + filename).length())); } catch (Exception ignoreException) { // NOTE: this could happen when we don't have permission to write to the specified directory // so let's log an error message to make this easier to debug. cfEngine.log("-] Failed to save attachment to " + attachDIR + filename + ", exception=[" + ignoreException.toString() + "]"); } } else { sd.setData("file", cfBooleanData.FALSE); sd.setData("content", new cfStringData("")); } AD.addElement(sd); } }
From source file:org.apache.axis2.transport.mail.SimpleMailListener.java
private void buildSOAPEnvelope(MimeMessage msg, MessageContext msgContext) throws AxisFault { //TODO we assume for the time being that there is only one attachement and this attachement contains the soap evelope try {//from w ww . j a v a 2 s. c om Multipart mp = (Multipart) msg.getContent(); if (mp != null) { for (int i = 0, n = mp.getCount(); i < n; i++) { Part part = mp.getBodyPart(i); String disposition = part.getDisposition(); if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) { String soapAction; /* Set the Charactorset Encoding */ String contentType = part.getContentType(); String charSetEncoding = BuilderUtil.getCharSetEncoding(contentType); if (charSetEncoding != null) { msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING, charSetEncoding); } else { msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING, MessageContext.DEFAULT_CHAR_SET_ENCODING); } /* SOAP Action */ soapAction = getMailHeaderFromPart(part, org.apache.axis2.transport.mail.Constants.HEADER_SOAP_ACTION); msgContext.setSoapAction(soapAction); String contentDescription = getMailHeaderFromPart(part, "Content-Description"); /* As an input stream - using the getInputStream() method. Any mail-specific encodings are decoded before this stream is returned.*/ if (contentDescription != null) { msgContext.setTo(new EndpointReference(contentDescription)); } if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) { TransportUtils.processContentTypeForAction(contentType, msgContext); } else { // According to the mail sepec, mail transport should support only // application/soap+xml; String message = "According to the mail sepec, mail transport " + "should support only application/soap+xml"; log.error(message); throw new AxisFault(message); } String cte = getMailHeaderFromPart(part, "Content-Transfer-Encoding"); if (!(cte != null && cte.equalsIgnoreCase("base64"))) { String message = "Processing of Content-Transfer-Encoding faild."; log.error(message); throw new AxisFault(message); } InputStream inputStream = part.getInputStream(); SOAPEnvelope envelope = TransportUtils.createSOAPMessage(msgContext, inputStream, contentType); msgContext.setEnvelope(envelope); } } } } catch (IOException e) { throw new AxisFault(e.getMessage(), e); } catch (MessagingException e) { throw new AxisFault(e.getMessage(), e); } catch (XMLStreamException e) { throw new AxisFault(e.getMessage(), e); } }
From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java
/** * Processes a part for a multi-part email. * * @param part the part to be processed. * @param message the message corresponding to the email. * @throws MessagingException//w w w . j a v a 2 s . c o m * @throws IOException */ public void processMailPart(Part part, Message message) throws MessagingException, IOException { if (!isTextPart(part)) { Object content = part.getContent(); if (content instanceof Multipart) { processMultipart((Multipart) content, message); } else { String fileName = getFileName(part); if (fileName != null) { Attachment attachment = new Attachment(); attachment.setSize(part.getSize()); attachment.setFileName(fileName); attachment.setContentType(extractContentType(part.getContentType())); String attachmentPath = saveAttachment(part, message.getComponentId(), message.getMessageId()); attachment.setPath(attachmentPath); message.getAttachments().add(attachment); } } } else { processBody((String) part.getContent(), extractContentType(part.getContentType()), message); } }
From source file:org.apache.solr.handler.dataimport.FsMailEntityProcessor.java
public boolean addPartToDocument(Part part, Map<String, Object> row, boolean outerMost) throws Exception { if (outerMost && part instanceof Message) { if (!addEnvelopToDocument(part, row)) { return false; }//from w w w . j a v a 2 s .com // store hash row.put(HASH, DigestUtils.md5Hex((String) row.get(FROM_CLEAN) + "" + (String) row.get(SUBJECT))); } String ct = part.getContentType(); ContentType ctype = new ContentType(ct); if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); int count = mp.getCount(); if (part.isMimeType("multipart/alternative")) { count = 1; } for (int i = 0; i < count; i++) { addPartToDocument(mp.getBodyPart(i), row, false); } } else if (part.isMimeType("message/rfc822")) { addPartToDocument((Part) part.getContent(), row, false); } else { String disp = part.getDisposition(); @SuppressWarnings("resource") // Tika will close stream InputStream is = part.getInputStream(); String fileName = part.getFileName(); Metadata md = new Metadata(); md.set(HttpHeaders.CONTENT_TYPE, ctype.getBaseType().toLowerCase(Locale.ROOT)); md.set(TikaMetadataKeys.RESOURCE_NAME_KEY, fileName); String content = this.tika.parseToString(is, md); if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) { if (row.get(ATTACHMENT) == null) { row.put(ATTACHMENT, new ArrayList<String>()); } List<String> contents = (List<String>) row.get(ATTACHMENT); contents.add(content); row.put(ATTACHMENT, contents); if (row.get(ATTACHMENT_NAMES) == null) { row.put(ATTACHMENT_NAMES, new ArrayList<String>()); } List<String> names = (List<String>) row.get(ATTACHMENT_NAMES); names.add(fileName); row.put(ATTACHMENT_NAMES, names); } else { if (row.get(CONTENT) == null) { row.put(CONTENT, new ArrayList<String>()); } List<String> contents = (List<String>) row.get(CONTENT); contents.add(content); row.put(CONTENT, contents); } } return true; }