List of usage examples for javax.mail BodyPart getInputStream
public InputStream getInputStream() throws IOException, MessagingException;
From source file:com.angstoverseer.service.mail.MailServiceImpl.java
@Override public void handleIncomingEmail(InputStream inputStream) { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); try {/* w w w.j av a 2 s. co m*/ MimeMessage mimeMessage = new MimeMessage(session, inputStream); Object messageContent = mimeMessage.getContent(); String message; if (messageContent instanceof Multipart) { Multipart mp = (Multipart) messageContent; BodyPart bodyPart = mp.getBodyPart(0); InputStream is = bodyPart.getInputStream(); message = convertStreamToString(is); } else { message = (String) messageContent; } Address sender = mimeMessage.getFrom()[0]; final String commandOutput = commandService.process(message, extractEmail(sender.toString())); sendResponseMail(sender, commandOutput, mimeMessage.getSubject()); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:de.saly.elasticsearch.support.IndexableMailMessage.java
public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent, final boolean withAttachments, final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException { final IndexableMailMessage im = new IndexableMailMessage(); @SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = jmm.getAllHeaders(); final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>(); while (allHeaders.hasMoreElements()) { final Header h = allHeaders.nextElement(); headerList.add(new IndexableHeader(h.getName(), h.getValue())); }// ww w . j a v a2s . c o m im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()])); im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields)); if (jmm.getFolder() instanceof POP3Folder) { im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm)); im.setMailboxType("POP"); } else { im.setMailboxType("IMAP"); } if (jmm.getFolder() instanceof UIDFolder) { im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm)); } im.setFolderFullName(jmm.getFolder().getFullName()); im.setFolderUri(jmm.getFolder().getURLName().toString()); im.setContentType(jmm.getContentType()); im.setSubject(jmm.getSubject()); im.setSize(jmm.getSize()); im.setSentDate(jmm.getSentDate()); if (jmm.getReceivedDate() != null) { im.setReceivedDate(jmm.getReceivedDate()); } if (jmm.getFrom() != null && jmm.getFrom().length > 0) { im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0])); } if (jmm.getRecipients(RecipientType.TO) != null) { im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO))); } if (jmm.getRecipients(RecipientType.CC) != null) { im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC))); } if (jmm.getRecipients(RecipientType.BCC) != null) { im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC))); } if (withTextContent) { // try { String textContent = getText(jmm, 0); if (stripTags) { textContent = stripTags(textContent); } im.setTextContent(textContent); // } catch (final Exception e) { // logger.error("Unable to retrieve text content for message {} due to {}", // e, ((MimeMessage) jmm).getMessageID(), e); // } } if (withAttachments) { try { final Object content = jmm.getContent(); // look for attachments if (jmm.isMimeType("multipart/*") && content instanceof Multipart) { List<ESAttachment> attachments = new ArrayList<ESAttachment>(); final Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { final BodyPart bodyPart = multipart.getBodyPart(i); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && !StringUtils.isNotBlank(bodyPart.getFileName())) { continue; // dealing with attachments only } final InputStream is = bodyPart.getInputStream(); final byte[] bytes = IOUtils.toByteArray(is); IOUtils.closeQuietly(is); attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName())); } if (!attachments.isEmpty()) { im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()])); im.setAttachmentCount(im.getAttachments().length); attachments.clear(); attachments = null; } } } catch (final Exception e) { logger.error( "Error indexing attachments (message will be indexed but without attachments) due to {}", e, e.toString()); } } im.setFlags(IMAPUtils.toStringArray(jmm.getFlags())); im.setFlaghashcode(jmm.getFlags().hashCode()); return im; }
From source file:org.eclipse.ecr.automation.server.jaxrs.io.MultiPartRequestReader.java
public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3, MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException { ExecutionRequest req = null;/*from ww w . ja va 2 s.c o m*/ try { List<String> ctypes = headers.get("Content-Type"); String ctype = ctypes.get(0); // we need to copy first the stream into a file otherwise it may // happen that // javax.mail fail to receive some parts - I am not sure why - // perhaps the stream is no more available when javax.mail need it? File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp"); FileUtils.copyToFile(in, tmp); in = new FileInputStream(tmp); // get the input from the saved // file try { MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype)); BodyPart part = mp.getBodyPart(0); // use content ids InputStream pin = part.getInputStream(); req = JsonRequestReader.readRequest(pin, headers); int cnt = mp.getCount(); if (cnt == 2) { // a blob req.setInput(readBlob(request, mp.getBodyPart(1))); } else if (cnt > 2) { // a blob list BlobList blobs = new BlobList(); for (int i = 1; i < cnt; i++) { blobs.add(readBlob(request, mp.getBodyPart(i))); } req.setInput(blobs); } else { log.error("Not all parts received."); for (int i = 0; i < cnt; i++) { log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> " + mp.getBodyPart(i).getContentType()); } throw ExceptionHandler.newException( new IllegalStateException("Received only " + cnt + " part in a multipart request")); } } finally { tmp.delete(); } } catch (Throwable e) { throw ExceptionHandler.newException("Failed to parse multipart request", e); } return req; }
From source file:org.nuxeo.ecm.automation.server.jaxrs.io.MultiPartRequestReader.java
@Override public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3, MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException { ExecutionRequest req = null;/*from w w w . j a v a 2s.c o m*/ try { List<String> ctypes = headers.get("Content-Type"); String ctype = ctypes.get(0); // we need to copy first the stream into a file otherwise it may // happen that // javax.mail fail to receive some parts - I am not sure why - // perhaps the stream is no more available when javax.mail need it? File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp"); FileUtils.copyToFile(in, tmp); in = new SharedFileInputStream(tmp); // get the input from the saved // file try { MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype)); BodyPart part = mp.getBodyPart(0); // use content ids InputStream pin = part.getInputStream(); req = JsonRequestReader.readRequest(pin, headers, getCoreSession()); int cnt = mp.getCount(); if (cnt == 2) { // a blob req.setInput(readBlob(request, mp.getBodyPart(1))); } else if (cnt > 2) { // a blob list BlobList blobs = new BlobList(); for (int i = 1; i < cnt; i++) { blobs.add(readBlob(request, mp.getBodyPart(i))); } req.setInput(blobs); } else { log.error("Not all parts received."); for (int i = 0; i < cnt; i++) { log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> " + mp.getBodyPart(i).getContentType()); } throw ExceptionHandler.newException( new IllegalStateException("Received only " + cnt + " part in a multipart request")); } } finally { tmp.delete(); } } catch (Throwable e) { throw ExceptionHandler.newException("Failed to parse multipart request", e); } return req; }
From source file:org.eclipse.ecr.automation.server.jaxrs.io.MultiPartFormRequestReader.java
public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3, MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException { ExecutionRequest req = null;/*from ww w.j a va 2 s .c o m*/ try { List<String> ctypes = headers.get("Content-Type"); String ctype = ctypes.get(0); // we need to copy first the stream into a file otherwise it may // happen that // javax.mail fail to receive some parts - I am not sure why - // perhaps the stream is no more available when javax.mail need it? File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp"); FileUtils.copyToFile(in, tmp); // get the input from the saved file in = new SharedFileInputStream(tmp); try { MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype)); BodyPart part = mp.getBodyPart(0); // use content ids InputStream pin = part.getInputStream(); req = JsonRequestReader.readRequest(pin, headers); int cnt = mp.getCount(); if (cnt == 2) { // a blob req.setInput(readBlob(request, mp.getBodyPart(1))); } else if (cnt > 2) { // a blob list BlobList blobs = new BlobList(); for (int i = 1; i < cnt; i++) { blobs.add(readBlob(request, mp.getBodyPart(i))); } req.setInput(blobs); } else { log.error("Not all parts received."); for (int i = 0; i < cnt; i++) { log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> " + mp.getBodyPart(i).getContentType()); } throw ExceptionHandler.newException( new IllegalStateException("Received only " + cnt + " part in a multipart request")); } } finally { try { in.close(); } catch (IOException e) { // do nothing } tmp.delete(); } } catch (Throwable e) { throw ExceptionHandler.newException("Failed to parse multipart request", e); } return req; }
From source file:org.nuxeo.ecm.automation.server.jaxrs.io.MultiPartFormRequestReader.java
@Override public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3, MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException { ExecutionRequest req = null;//from w ww. ja v a 2s. c o m try { List<String> ctypes = headers.get("Content-Type"); String ctype = ctypes.get(0); // we need to copy first the stream into a file otherwise it may // happen that // javax.mail fail to receive some parts - I am not sure why - // perhaps the stream is no more available when javax.mail need it? File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp"); FileUtils.copyToFile(in, tmp); // get the input from the saved file in = new SharedFileInputStream(tmp); try { MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype)); BodyPart part = mp.getBodyPart(0); // use content ids InputStream pin = part.getInputStream(); req = JsonRequestReader.readRequest(pin, headers, getCoreSession()); int cnt = mp.getCount(); if (cnt == 2) { // a blob req.setInput(readBlob(request, mp.getBodyPart(1))); } else if (cnt > 2) { // a blob list BlobList blobs = new BlobList(); for (int i = 1; i < cnt; i++) { blobs.add(readBlob(request, mp.getBodyPart(i))); } req.setInput(blobs); } else { log.error("Not all parts received."); for (int i = 0; i < cnt; i++) { log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> " + mp.getBodyPart(i).getContentType()); } throw ExceptionHandler.newException( new IllegalStateException("Received only " + cnt + " part in a multipart request")); } } finally { try { in.close(); } catch (IOException e) { // do nothing } tmp.delete(); } } catch (Throwable e) { throw ExceptionHandler.newException("Failed to parse multipart request", e); } return req; }
From source file:org.nuxeo.ecm.automation.jaxrs.io.operations.MultiPartRequestReader.java
@Override public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3, MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException { ExecutionRequest req = null;//from w w w . ja v a 2 s .c om try { List<String> ctypes = headers.get("Content-Type"); String ctype = ctypes.get(0); // we need to copy first the stream into a file otherwise it may // happen that // javax.mail fail to receive some parts - I am not sure why - // perhaps the stream is no more available when javax.mail need it? File tmp = Framework.createTempFile("nx-automation-mp-upload-", ".tmp"); FileUtils.copyToFile(in, tmp); in = new SharedFileInputStream(tmp); // get the input from the saved // file try { MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype)); BodyPart part = mp.getBodyPart(0); // use content ids InputStream pin = part.getInputStream(); JsonParser jp = factory.createJsonParser(pin); req = JsonRequestReader.readRequest(jp, headers, getCoreSession()); int cnt = mp.getCount(); if (cnt == 2) { // a blob req.setInput(readBlob(request, mp.getBodyPart(1))); } else if (cnt > 2) { // a blob list BlobList blobs = new BlobList(); for (int i = 1; i < cnt; i++) { blobs.add(readBlob(request, mp.getBodyPart(i))); } req.setInput(blobs); } else { log.error("Not all parts received."); for (int i = 0; i < cnt; i++) { log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> " + mp.getBodyPart(i).getContentType()); } throw WebException.newException( new IllegalStateException("Received only " + cnt + " part in a multipart request")); } } finally { tmp.delete(); } } catch (MessagingException | IOException e) { throw WebException.newException("Failed to parse multipart request", e); } return req; }
From source file:org.nuxeo.ecm.automation.jaxrs.io.operations.MultiPartFormRequestReader.java
@Override public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3, MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException { ExecutionRequest req = null;//from ww w . j a v a 2 s .co m try { List<String> ctypes = headers.get("Content-Type"); String ctype = ctypes.get(0); // we need to copy first the stream into a file otherwise it may // happen that // javax.mail fail to receive some parts - I am not sure why - // perhaps the stream is no more available when javax.mail need it? File tmp = Framework.createTempFile("nx-automation-mp-upload-", ".tmp"); FileUtils.copyToFile(in, tmp); // get the input from the saved file in = new SharedFileInputStream(tmp); try { MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype)); BodyPart part = mp.getBodyPart(0); // use content ids InputStream pin = part.getInputStream(); JsonParser jp = factory.createJsonParser(pin); req = JsonRequestReader.readRequest(jp, headers, getCoreSession()); int cnt = mp.getCount(); if (cnt == 2) { // a blob req.setInput(readBlob(request, mp.getBodyPart(1))); } else if (cnt > 2) { // a blob list BlobList blobs = new BlobList(); for (int i = 1; i < cnt; i++) { blobs.add(readBlob(request, mp.getBodyPart(i))); } req.setInput(blobs); } else { log.error("Not all parts received."); for (int i = 0; i < cnt; i++) { log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> " + mp.getBodyPart(i).getContentType()); } throw WebException.newException( new IllegalStateException("Received only " + cnt + " part in a multipart request")); } } finally { try { in.close(); } catch (IOException e) { // do nothing } tmp.delete(); } } catch (MessagingException | IOException e) { throw WebException.newException("Failed to parse multipart request", e); } return req; }
From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java
public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent, final boolean withHtmlContent, final boolean preferHtmlContent, final boolean withAttachments, final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException { final IndexableMailMessage im = new IndexableMailMessage(); @SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = jmm.getAllHeaders(); final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>(); while (allHeaders.hasMoreElements()) { final Header h = allHeaders.nextElement(); headerList.add(new IndexableHeader(h.getName(), h.getValue())); }//from w ww . ja v a 2 s .c o m im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()])); im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields)); if (jmm.getFolder() instanceof POP3Folder) { im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm)); im.setMailboxType("POP"); } else { im.setMailboxType("IMAP"); } if (jmm.getFolder() instanceof UIDFolder) { im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm)); } im.setFolderFullName(jmm.getFolder().getFullName()); im.setFolderUri(jmm.getFolder().getURLName().toString()); im.setContentType(jmm.getContentType()); im.setSubject(jmm.getSubject()); im.setSize(jmm.getSize()); im.setSentDate(jmm.getSentDate()); if (jmm.getReceivedDate() != null) { im.setReceivedDate(jmm.getReceivedDate()); } if (jmm.getFrom() != null && jmm.getFrom().length > 0) { im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0])); } if (jmm.getRecipients(RecipientType.TO) != null) { im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO))); } if (jmm.getRecipients(RecipientType.CC) != null) { im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC))); } if (jmm.getRecipients(RecipientType.BCC) != null) { im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC))); } if (withTextContent) { // try { String textContent = getText(jmm, 0, preferHtmlContent); if (stripTags) { textContent = stripTags(textContent); } im.setTextContent(textContent); // } catch (final Exception e) { // logger.error("Unable to retrieve text content for message {} due to {}", // e, ((MimeMessage) jmm).getMessageID(), e); // } } if (withHtmlContent) { // try { String htmlContent = getText(jmm, 0, true); im.setHtmlContent(htmlContent); // } catch (final Exception e) { // logger.error("Unable to retrieve text content for message {} due to {}", // e, ((MimeMessage) jmm).getMessageID(), e); // } } if (withAttachments) { try { final Object content = jmm.getContent(); // look for attachments if (jmm.isMimeType("multipart/*") && content instanceof Multipart) { List<ESAttachment> attachments = new ArrayList<ESAttachment>(); final Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { final BodyPart bodyPart = multipart.getBodyPart(i); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && !StringUtils.isNotBlank(bodyPart.getFileName())) { continue; // dealing with attachments only } final InputStream is = bodyPart.getInputStream(); final byte[] bytes = IOUtils.toByteArray(is); IOUtils.closeQuietly(is); attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName())); } if (!attachments.isEmpty()) { im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()])); im.setAttachmentCount(im.getAttachments().length); attachments.clear(); attachments = null; } } } catch (final Exception e) { logger.error( "Error indexing attachments (message will be indexed but without attachments) due to {}", e, e.toString()); } } im.setFlags(IMAPUtils.toStringArray(jmm.getFlags())); im.setFlaghashcode(jmm.getFlags().hashCode()); return im; }
From source file:org.alfresco.cacheserver.MultipartTest.java
private List<Patch> getPatches(String nodeId, long nodeVersion) throws MessagingException, IOException { List<Patch> patches = new LinkedList<>(); StringBuilder sb = new StringBuilder(); sb.append("/patch/"); sb.append(nodeId);/* w w w .j a va2 s. c o m*/ sb.append("/"); sb.append(nodeVersion); String url = sb.toString(); final ClientConfig config = new DefaultClientConfig(); config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); final Client client = Client.create(config); final WebResource resource = client.resource(url); final MimeMultipart response = resource.get(MimeMultipart.class); // This will iterate the individual parts of the multipart response for (int i = 0; i < response.getCount(); i++) { final BodyPart part = response.getBodyPart(i); System.out.printf("Embedded Body Part [Mime Type: %s, Length: %s]\n", part.getContentType(), part.getSize()); InputStream in = part.getInputStream(); // Patch patch = new Patch(); // patches.add(patch); } return patches; }