List of usage examples for javax.mail BodyPart getInputStream
public InputStream getInputStream() throws IOException, MessagingException;
From source file:com.ikon.util.MailUtils.java
/** * Add attachments to an imported mail./* ww w.j av a2 s. co m*/ */ public static void addAttachments(String token, com.ikon.bean.Mail mail, Part p, String userId) throws MessagingException, IOException, UnsupportedMimeTypeException, FileSizeExceededException, UserQuotaExceededException, VirusDetectedException, ItemExistsException, PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException { if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); int count = mp.getCount(); for (int i = 1; i < count; i++) { BodyPart bp = mp.getBodyPart(i); if (bp.getFileName() != null) { String name = MimeUtility.decodeText(bp.getFileName()); String fileName = FileUtils.getFileName(name); String fileExtension = FileUtils.getFileExtension(name); String testName = name; // Test if already exists a document with the same name in the mail for (int j = 1; OKMRepository.getInstance().hasNode(token, mail.getPath() + "/" + testName); j++) { // log.info("Trying with: {}", testName); testName = fileName + " (" + j + ")." + fileExtension; } Document attachment = new Document(); String mimeType = MimeTypeConfig.mimeTypes.getContentType(bp.getFileName().toLowerCase()); attachment.setMimeType(mimeType); attachment.setPath(mail.getPath() + "/" + testName); InputStream is = bp.getInputStream(); if (Config.REPOSITORY_NATIVE) { new DbDocumentModule().create(token, attachment, is, bp.getSize(), userId); } else { new JcrDocumentModule().create(token, attachment, is, userId); } is.close(); } } } }
From source file:com.openkm.util.MailUtils.java
/** * Add attachments to an imported mail.// www . j a v a 2s . c o m */ public static void addAttachments(String token, com.openkm.bean.Mail mail, Part p, String userId) throws MessagingException, IOException, UnsupportedMimeTypeException, FileSizeExceededException, UserQuotaExceededException, VirusDetectedException, ItemExistsException, PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException { if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); int count = mp.getCount(); for (int i = 1; i < count; i++) { BodyPart bp = mp.getBodyPart(i); if (bp.getFileName() != null) { String name = MimeUtility.decodeText(bp.getFileName()); String fileName = FileUtils.getFileName(name); String fileExtension = FileUtils.getFileExtension(name); String testName = name; // Test if already exists a document with the same name in the mail for (int j = 1; OKMRepository.getInstance().hasNode(token, mail.getPath() + "/" + testName); j++) { // log.info("Trying with: {}", testName); testName = fileName + " (" + j + ")." + fileExtension; } Document attachment = new Document(); String mimeType = MimeTypeConfig.mimeTypes.getContentType(bp.getFileName().toLowerCase()); attachment.setMimeType(mimeType); attachment.setPath(mail.getPath() + "/" + testName); InputStream is = bp.getInputStream(); if (Config.REPOSITORY_NATIVE) { new DbDocumentModule().create(token, attachment, is, bp.getSize(), userId); } else { new JcrDocumentModule().create(token, attachment, is, userId); } is.close(); } } } }
From source file:com.glaf.mail.business.MailBean.java
/** * ?/*w w w .jav a2 s. co m*/ * * @param part * @throws MessagingException * @throws IOException */ public void parseAttachment(Part part) throws MessagingException, IOException { String filename = ""; if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart mpart = mp.getBodyPart(i); String dispostion = mpart.getDisposition(); if ((dispostion != null) && (dispostion.equals(Part.ATTACHMENT) || dispostion.equals(Part.INLINE))) { filename = mpart.getFileName(); if (filename != null) { logger.debug("orig filename=" + filename); if (filename.indexOf("?") != -1) { filename = new String(filename.getBytes("GBK"), "UTF-8"); } if (filename.toLowerCase().indexOf("gb2312") != -1) { filename = MimeUtility.decodeText(filename); } filename = MailUtils.convertString(filename); logger.debug("filename=" + filename); parseFileContent(filename, mpart.getInputStream()); } } else if (mpart.isMimeType("multipart/*")) { parseAttachment(mpart); } else { filename = mpart.getFileName(); if (filename != null) { logger.debug("orig filename=" + filename); if (filename.indexOf("?") != -1) { filename = new String(filename.getBytes("GBK"), "UTF-8"); } if (filename.toLowerCase().indexOf("gb2312") != -1) { filename = MimeUtility.decodeText(filename); } filename = MailUtils.convertString(filename); parseFileContent(filename, mpart.getInputStream()); logger.debug("filename=" + filename); } } } } else if (part.isMimeType("message/rfc822")) { parseAttachment((Part) part.getContent()); } }
From source file:fr.gouv.culture.vitam.eml.EmlExtract.java
private static final String handleMultipartRecur(Multipart mp, Element identification, String id, VitamArgument argument, ConfigLoader config) throws MessagingException, IOException { int count = mp.getCount(); String result = ""; for (int i = 0; i < count; i++) { BodyPart bp = mp.getBodyPart(i); Object content = bp.getContent(); if (content instanceof String) { String[] cte = bp.getHeader("Content-Transfer-Encoding"); String[] aresult = null; if (cte != null && cte.length > 0) { aresult = extractContentType(bp.getContentType(), cte[0]); } else { aresult = extractContentType(bp.getContentType(), null); }/*from ww w .j a v a2s .c o m*/ Element emlroot = XmlDom.factory.createElement("body"); // <identity format="Internet Message Format" mime="message/rfc822" puid="fmt/278" extensions="eml"/> Element subidenti = XmlDom.factory.createElement("identification"); Element identity = XmlDom.factory.createElement("identity"); identity.addAttribute("format", "Internet Message Body Format"); identity.addAttribute("mime", aresult[0] != null ? aresult[0] : "unknown"); identity.addAttribute("extensions", aresult[3] != null ? aresult[3].substring(1) : "unknown"); if (aresult[1] != null) { identity.addAttribute("charset", aresult[1]); } identification.add(identity); emlroot.add(subidenti); identification.add(emlroot); //result += " " + saveBody((String) content.toString(), aresult, id, argument, config); result += " " + saveBody(bp.getInputStream(), aresult, id, argument, config); // ignore string } else if (content instanceof InputStream) { // handle input stream if (argument.extractKeyword) { result += " " + addSubIdentities(identification, bp, (InputStream) content, argument, config); } else { addSubIdentities(identification, bp, (InputStream) content, argument, config); } } else if (content instanceof Message) { Message message = (Message) content; if (argument.extractKeyword) { result += " " + handleMessageRecur(message, identification, id + "_" + i, argument, config); } else { handleMessageRecur(message, identification, id + "_" + i, argument, config); } } else if (content instanceof Multipart) { Multipart mp2 = (Multipart) content; if (argument.extractKeyword) { result += " " + handleMultipartRecur(mp2, identification, id + "_" + i, argument, config); } else { handleMultipartRecur(mp2, identification, id + "_" + i, argument, config); } } } return result; }
From source file:fr.gouv.culture.vitam.eml.EmlExtract.java
private static final String handleMultipart(Multipart mp, Element identification, String id, VitamArgument argument, ConfigLoader config) throws MessagingException, IOException { int count = mp.getCount(); String result = ""; identification.addAttribute(EMAIL_FIELDS.attNumber.name, Integer.toString(count - 1)); for (int i = 0; i < count; i++) { BodyPart bp = mp.getBodyPart(i); Object content = bp.getContent(); if (content instanceof String) { String[] cte = bp.getHeader("Content-Transfer-Encoding"); String[] aresult = null; if (cte != null && cte.length > 0) { aresult = extractContentType(bp.getContentType(), cte[0]); } else { aresult = extractContentType(bp.getContentType(), null); }//from w w w . j av a 2 s .c o m Element emlroot = XmlDom.factory.createElement("body"); // <identity format="Internet Message Format" mime="message/rfc822" puid="fmt/278" extensions="eml"/> Element subidenti = XmlDom.factory.createElement("identification"); Element identity = XmlDom.factory.createElement("identity"); identity.addAttribute("format", "Internet Message Body Format"); identity.addAttribute("mime", aresult[0] != null ? aresult[0] : "unknown"); identity.addAttribute("extensions", aresult[3] != null ? aresult[3].substring(1) : "unknown"); if (aresult[1] != null) { identity.addAttribute("charset", aresult[1]); } identification.add(identity); emlroot.add(subidenti); identification.add(emlroot); //result += " " + saveBody((String) content.toString(), aresult, id, argument, config); result += " " + saveBody(bp.getInputStream(), aresult, id, argument, config); } else if (content instanceof InputStream) { // handle input stream if (argument.extractKeyword) { result += " " + addSubIdentities(identification, bp, (InputStream) content, argument, config); } else { addSubIdentities(identification, bp, (InputStream) content, argument, config); } ((InputStream) content).close(); } else if (content instanceof Message) { Message message = (Message) content; // XXX perhaps using Commands.addFormatIdentification Element emlroot = XmlDom.factory.createElement(EMAIL_FIELDS.formatEML.name); // <identity format="Internet Message Format" mime="message/rfc822" puid="fmt/278" extensions="eml"/> Element subidenti = XmlDom.factory.createElement("identification"); Element identity = XmlDom.factory.createElement("identity"); identity.addAttribute("format", "Internet Message Format"); identity.addAttribute("mime", "message/rfc822"); identity.addAttribute("puid", "fmt/278"); identity.addAttribute("extensions", "eml"); identification.add(identity); emlroot.add(subidenti); identification.add(emlroot); if (argument.extractKeyword) { result += " " + extractInfoMessage((MimeMessage) message, emlroot, argument, config); } else { extractInfoMessage((MimeMessage) message, emlroot, argument, config); } } else if (content instanceof Multipart) { Multipart mp2 = (Multipart) content; if (argument.extractKeyword) { result += " " + handleMultipartRecur(mp2, identification, id + "_" + i, argument, config); } else { handleMultipartRecur(mp2, identification, id + "_" + i, argument, config); } } } return result; }
From source file:mitm.application.djigzo.james.mailets.PDFEncryptTest.java
private void checkEncryption(MimeMessage message, String password, boolean hasReplyLink) throws Exception { /*//from w w w. j av a2 s .c o m * The message should be a mime multipart mixed with two parts. The first part should be readable text * and the second part should be the encrypted PDF */ assertTrue(message.isMimeType("multipart/mixed")); Multipart mp = (Multipart) message.getContent(); assertEquals(2, mp.getCount()); BodyPart textPart = mp.getBodyPart(0); assertTrue(textPart.isMimeType("text/plain")); BodyPart pdfPart = mp.getBodyPart(1); assertTrue(pdfPart.isMimeType("application/pdf")); PdfReader reader = new PdfReader(pdfPart.getInputStream(), password.getBytes(CharacterEncoding.US_ASCII)); String firstPageContent = new String(reader.getPageContent(1), CharacterEncoding.US_ASCII); /* * We just check whether the raw content contains (Reply) or not. */ if (hasReplyLink) { assertTrue(firstPageContent.contains("(Reply)")); assertTrue(((String) textPart.getContent()).contains("reply URL: http://127.0.0.1?env=")); } else { assertFalse(firstPageContent.contains("(Reply)")); } }
From source file:org.sakaiproject.nakamura.smtp.SakaiSmtpServer.java
private void writePartAsFile(Session session, BodyPart part, String nodeName, Content parentNode) throws AccessDeniedException, StorageClientException, MessagingException, IOException { // String filePath = parentNode.getPath() + "/nt:file"; // String fileContentPath = filePath + "/jcr:content"; // session.getContentManager().update( // new Content(filePath, new HashMap<String, Object>())); // session.getContentManager().update(new Content(fileContentPath, new HashMap<String, // Object>())); // Content resourceNode = session.getContentManager().get(fileContentPath); // resourceNode.setProperty("jcr:primaryType", "nt:resource"); /*/* w w w .j ava 2 s. co m*/ * Instead of creating a child node, just write the body part to the parentNode. I * think this will work, but may collide/override properties already set on the * message content. Let's ensure there are no collisions. */ if (!parentNode.hasProperty(Content.MIMETYPE_FIELD)) { parentNode.setProperty(Content.MIMETYPE_FIELD, part.getContentType()); } else { if (part.getContentType().equals(parentNode.getProperty(Content.MIMETYPE_FIELD))) { LOGGER.debug("Same mimeType; no worries"); } else { throw new IllegalStateException( "This sparse approach is bust; must create a subpath for file body"); } } // parentNode.setProperty("jcr:data", part.getInputStream()); session.getContentManager().writeBody(parentNode.getPath(), part.getInputStream()); }
From source file:com.zimbra.cs.mailbox.calendar.Invite.java
/** * Returns the meeting notes. Meeting notes is the text/plain part in an * invite. It typically includes CUA-generated meeting summary as well as * text entered by the user./* w w w . j a va2 s. c o m*/ * * @return null if notes is not found * @throws ServiceException */ public static String getDescription(Part mmInv, String mimeType) throws ServiceException { if (mmInv == null) return null; try { // If top-level is text/calendar, parse the iCalendar object and return // the DESCRIPTION of the first VEVENT/VTODO encountered. String mmCtStr = mmInv.getContentType(); if (mmCtStr != null) { ContentType mmCt = new ContentType(mmCtStr); if (mmCt.match(MimeConstants.CT_TEXT_CALENDAR)) { boolean wantHtml = MimeConstants.CT_TEXT_HTML.equalsIgnoreCase(mimeType); Object mmInvContent = mmInv.getContent(); InputStream is = null; try { String charset = MimeConstants.P_CHARSET_UTF8; if (mmInvContent instanceof InputStream) { charset = mmCt.getParameter(MimeConstants.P_CHARSET); if (charset == null) charset = MimeConstants.P_CHARSET_UTF8; is = (InputStream) mmInvContent; } else if (mmInvContent instanceof String) { String str = (String) mmInvContent; charset = MimeConstants.P_CHARSET_UTF8; is = new ByteArrayInputStream(str.getBytes(charset)); } if (is != null) { ZVCalendar iCal = ZCalendarBuilder.build(is, charset); for (Iterator<ZComponent> compIter = iCal.getComponentIterator(); compIter.hasNext();) { ZComponent component = compIter.next(); ICalTok compTypeTok = component.getTok(); if (compTypeTok == ICalTok.VEVENT || compTypeTok == ICalTok.VTODO) { if (!wantHtml) return component.getPropVal(ICalTok.DESCRIPTION, null); else return component.getDescriptionHtml(); } } } } finally { ByteUtil.closeStream(is); } } } Object mmInvContent = mmInv.getContent(); if (!(mmInvContent instanceof MimeMultipart)) { if (mmInvContent instanceof InputStream) { ByteUtil.closeStream((InputStream) mmInvContent); } return null; } MimeMultipart mm = (MimeMultipart) mmInvContent; // If top-level is multipart, get description from text/* part. int numParts = mm.getCount(); String charset = null; for (int i = 0; i < numParts; i++) { BodyPart part = mm.getBodyPart(i); String ctStr = part.getContentType(); try { ContentType ct = new ContentType(ctStr); if (ct.match(mimeType)) { charset = ct.getParameter(MimeConstants.P_CHARSET); if (charset == null) charset = MimeConstants.P_CHARSET_DEFAULT; byte[] descBytes = ByteUtil.getContent(part.getInputStream(), part.getSize()); return new String(descBytes, charset); } // If part is a multipart, recurse. if (ct.getBaseType().matches(MimeConstants.CT_MULTIPART_WILD)) { String str = getDescription(part, mimeType); if (str != null) { return str; } } } catch (javax.mail.internet.ParseException e) { ZimbraLog.calendar.warn("Invalid Content-Type found: \"" + ctStr + "\"; skipping part", e); } } } catch (IOException e) { throw ServiceException.FAILURE("Unable to get calendar item notes MIME part", e); } catch (MessagingException e) { throw ServiceException.FAILURE("Unable to get calendar item notes MIME part", e); } return null; }
From source file:immf.SendMailBridge.java
private void parseBodypart(SenderMail sendMail, BodyPart bp, String subtype, String parentSubtype) throws IOException { boolean limiterr = false; String badfile = null;//from w w w . j a v a2 s . co m try { String contentType = bp.getContentType().toLowerCase(); log.info("Bodypart ContentType:" + contentType); log.info("subtype:" + subtype); if (contentType.startsWith("multipart/")) { parseMultipart(sendMail, (Multipart) bp.getContent(), getSubtype(contentType), subtype); } else if (sendMail.getPlainTextContent() == null && contentType.startsWith("text/plain")) { // ???plain/text? String content = (String) bp.getContent(); log.info("set Content text [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); sendMail.setPlainTextContent(content); } else if (sendMail.getHtmlContent() == null && contentType.startsWith("text/html") && (subtype.equalsIgnoreCase("alternative") || subtype.equalsIgnoreCase("related"))) { String content = (String) bp.getContent(); log.info("set Content html [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); // html???? sendMail.setHtmlContent(content); } else if (contentType.startsWith("text/html")) { // subtype?mixed?? String content = (String) bp.getContent(); if (sendMail.getHtmlContent() == null) { // text/plain???????? text/html????????? log.info("set Content html [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); // html???? sendMail.setHtmlContent(content); } else { log.info("Discarding duplicate content [" + content + "]"); } } else { log.debug("attach"); // ???? if (subtype.equalsIgnoreCase("related")) { // SenderAttachment file = new SenderAttachment(); String fname = uniqId(); String fname2 = Util.getFileName(bp); // iPhone?gifpng?????????????ContentType(?png???gif?) if (getSubtype(contentType).equalsIgnoreCase("png")) { file.setContentType("image/gif"); fname = fname + ".gif"; fname2 = getBasename(fname2) + ".gif"; file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream()))); } else { file.setContentType(contentType); fname = fname + "." + getSubtype(contentType); file.setData(inputstream2bytes(bp.getInputStream())); } file.setInline(true); boolean inline = !this.forcePlainText & sendMail.checkAttachmentCapability(file); if (!inline) { file.setInline(false); if (!sendMail.checkAttachmentCapability(file)) { limiterr = true; badfile = fname2; throw new Exception("Attachments: size limit or file count limit exceeds!"); } } if (inline) { file.setFilename(fname); file.setContentId(bp.getHeader("Content-Id")[0]); log.info("Inline Attachment " + file.loggingString() + ", Hash:" + file.getHash()); } else { file.setFilename(fname2); log.info("Attachment " + file.loggingString()); } sendMail.addAttachmentFileIdList(file); } else { // ? SenderAttachment file = new SenderAttachment(); file.setInline(false); file.setContentType(contentType); String fname = Util.getFileName(bp); if (getSubtype(contentType).equalsIgnoreCase("png")) { file.setContentType("image/gif"); file.setFilename(getBasename(fname) + ".gif"); file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream()))); } else { file.setFilename(fname); file.setData(inputstream2bytes(bp.getInputStream())); } if (!sendMail.checkAttachmentCapability(file)) { limiterr = true; badfile = file.getFilename(); throw new Exception("Attachments: size limit or file count limit exceeds!"); } sendMail.addAttachmentFileIdList(file); log.info("Attachment " + file.loggingString()); } } } catch (Exception e) { log.error("parse bodypart error.", e); if (limiterr) { sendMail.addPlainTextContent("\n[(" + badfile + ")]"); if (sendMail.getHtmlContent() != null) { sendMail.addHtmlContent("[(" + badfile + ")]<br>"); } } else { throw new IOException("BodyPart error." + e.getMessage(), e); } } }