List of usage examples for javax.mail Multipart getBodyPart
public synchronized BodyPart getBodyPart(int index) throws MessagingException
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;/* w w w . j a v a 2s .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.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 {/* ww w . j a v a 2 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: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 {/* w w w. j a v a 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.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);/*from ww w.ja va 2s .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:org.alfresco.repo.content.transform.EmailToPDFContentTransformer.java
/** * Do txt transform of eml file.// www.j a v a2s . c o m * * @param is * the input stream * @param os * the final output stream * @param inputMime * the input mime type * @param targetMimeType * the target mime type * @param encoding * the encoding of reader * @param writerEncoding * the writer encoding * @throws IOException * Signals that an I/O exception has occurred. * @throws TransformerConfigurationException * the transformer configuration exception * @throws SAXException * the sAX exception * @throws TikaException * the tika exception * @throws MessagingException * the messaging exception */ protected void doTxtTransform(InputStream is, OutputStream os, String inputMime, String targetMimeType, String encoding, String writerEncoding) throws IOException, TransformerConfigurationException, SAXException, TikaException, MessagingException { MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()), is); final StringBuilder sb = new StringBuilder(); Object content = mimeMessage.getContent(); if (content instanceof Multipart) { Multipart multipart = (Multipart) content; Part part = multipart.getBodyPart(0); if (part.getContent() instanceof Multipart) { multipart = (Multipart) part.getContent(); for (int i = 0, n = multipart.getCount(); i < n; i++) { part = multipart.getBodyPart(i); if (part.isMimeType("text/*")) { sb.append(part.getContent().toString()).append("\n"); } } } else if (part.isMimeType("text/*")) { sb.append(part.getContent().toString()); } } else { sb.append(content.toString()); } textToPDF(new ByteArrayInputStream(sb.toString().getBytes()), UTF_8, os); }
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 w w . ja v a2s.c om*/ * @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); }
From source file:org.simplejavamail.internal.util.MimeMessageParser.java
/** * Extracts the content of a MimeMessage recursively. * * @param part the current MimePart//from w ww . java 2s . c o m * @throws MessagingException parsing the MimeMessage failed * @throws IOException parsing the MimeMessage failed */ private void parse(final MimePart part) throws MessagingException, IOException { extractCustomUserHeaders(part); if (isMimeType(part, "text/plain") && plainContent == null && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { plainContent = (String) part.getContent(); } else { if (isMimeType(part, "text/html") && htmlContent == null && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { htmlContent = (String) part.getContent(); } else { if (isMimeType(part, "multipart/*")) { final Multipart mp = (Multipart) part.getContent(); final int count = mp.getCount(); // iterate over all MimeBodyPart for (int i = 0; i < count; i++) { parse((MimeBodyPart) mp.getBodyPart(i)); } } else { final DataSource ds = createDataSource(part); // If the diposition is not provided, the part should be treat as attachment if (part.getDisposition() == null || Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { this.attachmentList.put(part.getContentID(), ds); } else if (Part.INLINE.equalsIgnoreCase(part.getDisposition())) { this.cidMap.put(part.getContentID(), ds); } else { throw new IllegalStateException("invalid attachment type"); } } } } }
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. * //from w w w .ja 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.geoserver.wcs.GetCoverageTest.java
@Test public void testRasterFilterGreen() throws Exception { String queryString = "wcs?identifier=" + getLayerId(MOSAIC) + "&request=getcoverage" + "&service=wcs&version=1.1.1&&format=image/tiff" + "&BoundingBox=0,0,1,1,urn:ogc:def:crs:EPSG:6.6:4326" + "&CQL_FILTER=location like 'green%25'"; MockHttpServletResponse response = getAsServletResponse(queryString); // 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 pixel int[] pixel = new int[3]; image.getData().getPixel(0, 0, pixel); assertEquals(0, pixel[0]);//from w w w . j a v a 2 s .c o m assertEquals(255, pixel[1]); assertEquals(0, pixel[2]); }
From source file:org.geoserver.wcs.GetCoverageTest.java
@Test public void testRasterFilterRed() throws Exception { String queryString = "wcs?identifier=" + getLayerId(MOSAIC) + "&request=getcoverage" + "&service=wcs&version=1.1.1&&format=image/tiff" + "&BoundingBox=0,0,1,1,urn:ogc:def:crs:EPSG:6.6:4326" + "&CQL_FILTER=location like 'red%25'"; MockHttpServletResponse response = getAsServletResponse(queryString); // 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 pixel int[] pixel = new int[3]; image.getData().getPixel(0, 0, pixel); assertEquals(255, pixel[0]);//from w w w . jav a2 s.co m assertEquals(0, pixel[1]); assertEquals(0, pixel[2]); }