List of usage examples for javax.mail Multipart getCount
public synchronized int getCount() throws MessagingException
From source file:org.nuxeo.ecm.platform.mail.listener.action.ExtractMessageInformationAction.java
protected void getAttachmentParts(Part part, String defaultFilename, MimetypeRegistry mimeService, ExecutionContext context) throws MessagingException, IOException { String filename = getFilename(part, defaultFilename); List<Blob> blobs = (List<Blob>) context.get(ATTACHMENTS_KEY); if (part.isMimeType("multipart/alternative")) { bodyContent += getText(part);// w w w. jav a 2 s .c o m } else { if (!part.isMimeType("multipart/*")) { String disp = part.getDisposition(); // no disposition => mail body, which can be also blob (image for // instance) if (disp == null && // convert only text part.getContentType().toLowerCase().startsWith("text/")) { bodyContent += decodeMailBody(part); } else { Blob blob; try (InputStream in = part.getInputStream()) { blob = Blobs.createBlob(in); } String mime = DEFAULT_BINARY_MIMETYPE; try { if (mimeService != null) { ContentType contentType = new ContentType(part.getContentType()); mime = mimeService.getMimetypeFromFilenameAndBlobWithDefault(filename, blob, contentType.getBaseType()); } } catch (MessagingException | MimetypeDetectionException e) { log.error(e); } blob.setMimeType(mime); blob.setFilename(filename); blobs.add(blob); } } if (part.isMimeType("multipart/*")) { // This is a Multipart Multipart mp = (Multipart) part.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) { getAttachmentParts(mp.getBodyPart(i), defaultFilename, mimeService, context); } } else if (part.isMimeType(MESSAGE_RFC822_MIMETYPE)) { // This is a Nested Message getAttachmentParts((Part) part.getContent(), defaultFilename, mimeService, context); } } }
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 {//from w w w . j ava 2s.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.campware.cream.modules.scheduledjobs.Pop3Job.java
private String handleAlternative(Object o, String content) throws Exception { Multipart multipart = (Multipart) o; for (int k = 0, n = multipart.getCount(); k < n; k++) { Part part = multipart.getBodyPart(k); MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/html")) { log.debug("---------------> Handle html alternative. "); content += (String) part.getContent(); }/*from ww w.jav a 2 s . c o m*/ } return content; }
From source file:org.xwiki.platform.notifications.test.ui.NotificationsTest.java
@Test public void testNotificationsEmails() throws Exception { getUtil().login(SECOND_USER_NAME, SECOND_USER_PASSWORD); NotificationsUserProfilePage p;/* www . j av a 2 s . c o m*/ p = NotificationsUserProfilePage.gotoPage(SECOND_USER_NAME); p.setPageCreatedEmail(true); getUtil().login(FIRST_USER_NAME, FIRST_USER_PASSWORD); DocumentReference page1 = new DocumentReference("xwiki", getTestClassName(), "Page1"); DocumentReference page2 = new DocumentReference("xwiki", getTestClassName(), "Page2"); getUtil().createPage(getTestClassName(), "Page1", "Content 1", "Title 1"); getUtil().createPage(getTestClassName(), "Page2", "Content 2", "Title 2"); // Trigger the notification email job getUtil().login(SUPERADMIN_USER_NAME, SUPERADMIN_PASSWORD); SchedulerHomePage schedulerHomePage = SchedulerHomePage.gotoPage(); schedulerHomePage.clickJobActionTrigger("Notifications daily email"); this.mail.waitForIncomingEmail(1); assertEquals(1, this.mail.getReceivedMessages().length); MimeMessage message = this.mail.getReceivedMessages()[0]; assertTrue(message.getSubject().endsWith("event(s) on the wiki")); Multipart content = (Multipart) message.getContent(); assertTrue(content.getContentType().startsWith("multipart/mixed;")); assertEquals(1, content.getCount()); MimeBodyPart mimeBodyPart1 = (MimeBodyPart) content.getBodyPart(0); Multipart multipart1 = (Multipart) mimeBodyPart1.getContent(); assertEquals(2, multipart1.getCount()); assertEquals("text/plain; charset=UTF-8", multipart1.getBodyPart(0).getContentType()); assertEquals("text/html; charset=UTF-8", multipart1.getBodyPart(1).getContentType()); // Events inside an email comes in random order, so we just verify that all the expected content is there String email = prepareMail(multipart1.getBodyPart(0).getContent().toString()); assertTrue(email .contains(prepareMail(IOUtils.toString(getClass().getResourceAsStream("/expectedMail1.txt"))))); assertTrue(email .contains(prepareMail(IOUtils.toString(getClass().getResourceAsStream("/expectedMail2.txt"))))); assertTrue(email .contains(prepareMail(IOUtils.toString(getClass().getResourceAsStream("/expectedMail3.txt"))))); getUtil().rest().delete(page1); getUtil().rest().delete(page2); }
From source file:org.nuxeo.ecm.platform.mail.listener.action.ExtractMessageInformationAction.java
/** * Return the primary text content of the message. *///from w w w .ja va2 s. co m private String getText(Part p) throws MessagingException, IOException { if (p.isMimeType("text/*")) { return decodeMailBody(p); } 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 = getText(bp); } continue; } else if (bp.isMimeType("text/html")) { String s = getText(bp); if (s != null) { return s; } } else { return getText(bp); } } return text; } else if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); for (int i = 0; i < mp.getCount(); i++) { String s = getText(mp.getBodyPart(i)); if (s != null) { return s; } } } return null; }
From source file:de.contentreich.alfresco.repo.email.EMLTransformer.java
private void processPreviewMultiPart(Multipart multipart, Map<String, String> parts) throws MessagingException, IOException { logger.debug("Processing multipart of type {}", multipart.getContentType()); // FIXME : Implement strict Depth or breadth first ? for (int i = 0, n = multipart.getCount(); i < n; i++) { Part part = multipart.getBodyPart(i); logger.debug("Processing part name {}, disposition = {}, type type = {}", new Object[] { part.getFileName(), part.getDisposition(), part.getContentType() }); if (part.getContent() instanceof Multipart) { processPreviewMultiPart((Multipart) part.getContent(), parts); } else if (part.getContentType().contains("text")) { String key = part.getContentType().split(";")[0]; String content = null; logger.debug("Add part with content type {} using key {}", part.getContentType(), key); if (key.endsWith("html")) { // <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> // Breaks preview ! content = part.getContent().toString().replaceAll("(?i)(?s)<meta.*charset=[^>]*>", ""); } else { content = part.getContent().toString(); }/*from w w w . j av a 2 s. c om*/ appendPreviewContent(parts, key, content); } } }
From source file:com.szmslab.quickjavamail.receive.MessageLoader.java
/** * ?????MessageContent????/*from w ww . j av a2 s. co m*/ * * @param multiPart * ? * @param msgContent * ???? * @throws MessagingException * @throws IOException */ private void setMultipartContent(Multipart multiPart, MessageContent msgContent) throws MessagingException, IOException { for (int i = 0; i < multiPart.getCount(); i++) { Part part = multiPart.getBodyPart(i); if (part.getContentType().indexOf("multipart") >= 0) { setMultipartContent((Multipart) part.getContent(), msgContent); } else { String disposition = part.getDisposition(); if (Part.ATTACHMENT.equals(disposition)) { // Disposition?"attachment"???ContentType???? msgContent.attachmentFileList.add(new AttachmentFile(MimeUtility.decodeText(part.getFileName()), part.getDataHandler().getDataSource())); } else { if (part.isMimeType("text/html")) { msgContent.html = part.getContent().toString(); } else if (part.isMimeType("text/plain")) { msgContent.text = part.getContent().toString(); } else { // Disposition?"inline"???ContentType?? if (Part.INLINE.equals(disposition)) { String cid = ""; if (part instanceof MimeBodyPart) { MimeBodyPart mimePart = (MimeBodyPart) part; cid = mimePart.getContentID(); } msgContent.inlineImageFileList .add(new InlineImageFile(cid, MimeUtility.decodeText(part.getFileName()), part.getDataHandler().getDataSource())); } } } } } }
From source file:org.apache.james.transport.mailets.StripAttachment.java
/** * Checks every part in this part (if it is a Multipart) for having a * filename that matches the pattern. If the name matches, the content of * the part is stored (using its name) in te given diretcory. * /* w ww .j a v a 2 s . c o m*/ * Note: this method is recursive. * * @param part * The part to analyse. * @param mail * @return * @throws Exception */ private boolean analyseMultipartPartMessage(Part part, Mail mail) throws Exception { if (part.isMimeType("multipart/*")) { try { Multipart multipart = (Multipart) part.getContent(); boolean atLeastOneRemoved = false; int numParts = multipart.getCount(); for (int i = 0; i < numParts; i++) { Part p = multipart.getBodyPart(i); if (p.isMimeType("multipart/*")) { atLeastOneRemoved |= analyseMultipartPartMessage(p, mail); } else { boolean removed = checkMessageRemoved(p, mail); if (removed) { multipart.removeBodyPart(i); atLeastOneRemoved = true; i--; numParts--; } } } if (atLeastOneRemoved) { part.setContent(multipart); if (part instanceof Message) { ((Message) part).saveChanges(); } } return atLeastOneRemoved; } catch (Exception e) { log("Could not analyse part.", e); } } return false; }
From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java
private String handleMulitipart(Object o, String content, InboxEvent inboxentry) throws Exception { Multipart multipart = (Multipart) o; for (int k = 0, n = multipart.getCount(); k < n; k++) { Part part = multipart.getBodyPart(k); String disposition = part.getDisposition(); MimeBodyPart mbp = (MimeBodyPart) part; if ((disposition != null) && (disposition.equals(Part.ATTACHMENT))) { log.debug("---------------> Saving File " + part.getFileName() + " " + part.getContent()); saveAttachment(part, inboxentry); } else {//from w w w . j a v a2 s . c o m // Check if plain if (mbp.isMimeType("text/plain")) { log.debug("---------------> Handle plain. "); content += "<PRE style=\"font-size: 12px;\">" + (String) part.getContent() + "</PRE>"; // Check if html } else if (mbp.isMimeType("text/html")) { log.debug("---------------> Handle plain. "); content += (String) part.getContent(); } else { // Special non-attachment cases here of // image/gif, text/html, ... log.debug("---------------> Special non-attachment cases " + " " + part.getContentType()); if (mbp.isMimeType("multipart/*")) { Object ob = part.getContent(); content = this.handleMulitipart(ob, content, inboxentry) + "\n\n" + content; } else { saveAttachment(part, inboxentry); } } } } return content; }
From source file:org.geoserver.wcs.GetCoverageTest.java
/** * This tests just ended up throwing an exception as the coverage being encoded * was too large due to a bug in the scales estimation * //from w ww . j a v a 2 s .co m * @throws Exception */ @Test public void testRotatedGet() throws Exception { String request = "wcs?&service=WCS&request=GetCoverage&version=1.1.1&identifier=RotatedCad&BoundingBox=7.7634071540971386,45.14712131948007,7.76437367395267,45.14764567708965,urn:ogc:def:crs:OGC:1.3:CRS84&Format=image/tiff"; MockHttpServletResponse response = getAsServletResponse(request); // parse the multipart, check there are two parts Multipart multipart = getMultipart(response); assertEquals(2, multipart.getCount()); BodyPart coveragePart = multipart.getBodyPart(1); assertEquals("image/tiff", coveragePart.getContentType()); assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]); // make sure we can read the coverage back ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next(); reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream())); RenderedImage image = reader.read(0); // check the image is suitably small (without requiring an exact size) assertTrue(image.getWidth() < 1000); assertTrue(image.getHeight() < 1000); }