List of usage examples for javax.mail.internet MimeMultipart getCount
@Override public synchronized int getCount() throws MessagingException
From source file:net.prhin.mailman.MailMan.java
public static void main(String[] args) { Properties props = new Properties(); props.setProperty(resourceBundle.getString("mailman.mail.store"), resourceBundle.getString("mailman.protocol")); Session session = Session.getInstance(props); try {/*from w w w . j a va 2 s .c om*/ Store store = session.getStore(); store.connect(resourceBundle.getString("mailman.host"), resourceBundle.getString("mailman.user"), resourceBundle.getString("mailman.password")); Folder inbox = store.getFolder(resourceBundle.getString("mailman.folder")); inbox.open(Folder.READ_ONLY); inbox.getUnreadMessageCount(); Message[] messages = inbox.getMessages(); for (int i = 0; i <= messages.length / 2; i++) { Message tmpMessage = messages[i]; Multipart multipart = (Multipart) tmpMessage.getContent(); System.out.println("Multipart count: " + multipart.getCount()); for (int j = 0; j < multipart.getCount(); j++) { BodyPart bodyPart = multipart.getBodyPart(j); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) { if (bodyPart.getContent().getClass().equals(MimeMultipart.class)) { MimeMultipart mimeMultipart = (MimeMultipart) bodyPart.getContent(); for (int k = 0; k < mimeMultipart.getCount(); k++) { if (mimeMultipart.getBodyPart(k).getFileName() != null) { printFileContents(mimeMultipart.getBodyPart(k)); } } } } else { printFileContents(bodyPart); } } } inbox.close(false); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:Main.java
public static boolean isContainAttachment(Part part) throws MessagingException, IOException { boolean flag = false; if (part.isMimeType("multipart/*")) { MimeMultipart multipart = (MimeMultipart) part.getContent(); int partCount = multipart.getCount(); for (int i = 0; i < partCount; i++) { BodyPart bodyPart = multipart.getBodyPart(i); String disp = bodyPart.getDisposition(); if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { flag = true;/*from w w w . j a v a2s .co m*/ } else if (bodyPart.isMimeType("multipart/*")) { flag = isContainAttachment(bodyPart); } else { String contentType = bodyPart.getContentType(); if (contentType.indexOf("application") != -1) { flag = true; } if (contentType.indexOf("name") != -1) { flag = true; } } if (flag) break; } } else if (part.isMimeType("message/rfc822")) { flag = isContainAttachment((Part) part.getContent()); } return flag; }
From source file:mailbox.CreationViaEmail.java
private static Content getJoinedContent(MimePart part) throws IOException, MessagingException { Content result = new Content(); MimeMultipart mp = (MimeMultipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { MimeBodyPart p = (MimeBodyPart) mp.getBodyPart(i); result.merge(processPart(p, part)); }/*from w ww . j a va 2s. c o m*/ return result; }
From source file:mailbox.CreationViaEmail.java
private static Content getContentOfBestPart(MimePart part, MimePart parent) throws IOException, MessagingException { MimeBodyPart best = null;//from www . jav a 2 s. c o m MimeMultipart mp = (MimeMultipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { // Prefer HTML if the parent is a multipart/related part which may contain // inline images, because text/plain cannot embed the images. boolean isHtmlPreferred = parent != null && parent.isMimeType(MimeType.MULTIPART_RELATED); best = better((MimeBodyPart) mp.getBodyPart(i), best, isHtmlPreferred); } return processPart(best, part); }
From source file:mailbox.CreationViaEmail.java
private static Content getContentWithAttachments(MimePart part) throws MessagingException, IOException { Content result = new Content(); String rootId = new ContentType(part.getContentType()).getParameter("start"); MimeMultipart mp = (MimeMultipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { MimePart p = (MimePart) mp.getBodyPart(i); if (isRootPart(p, i, rootId)) { result = result.merge(processPart(p, part)); } else {/*from w ww .j a v a 2 s.c om*/ result.attachments.add(p); } } return result; }
From source file:com.zimbra.cs.util.SpamExtract.java
private static void writeAttachedMessages(MimeMessage mm, File outdir, String msgUri) throws IOException, MessagingException { // Not raw - ignore the spam report and extract messages that are in attachments... if (!(mm.getContent() instanceof MimeMultipart)) { LOG.warn("Spam/notspam messages must have attachments (skipping " + msgUri + ")"); return;//from ww w .ja v a 2 s .c om } MimeMultipart mmp = (MimeMultipart) mm.getContent(); int nAttachments = mmp.getCount(); boolean foundAtleastOneAttachedMessage = false; for (int i = 0; i < nAttachments; i++) { BodyPart bp = mmp.getBodyPart(i); if (!bp.isMimeType("message/rfc822")) { // Let's ignore all parts that are not messages. continue; } foundAtleastOneAttachedMessage = true; Part msg = (Part) bp.getContent(); // the actual message File file = new File(outdir, mOutputPrefix + "-" + mExtractIndex++); OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(file)); if (msg instanceof MimeMessage) { //bug 74435 clone into newMsg so our parser has a chance to handle headers which choke javamail ZMimeMessage newMsg = new ZMimeMessage((MimeMessage) msg); newMsg.writeTo(os); } else { msg.writeTo(os); } } finally { os.close(); } if (verbose) LOG.info("Wrote: " + file); } if (!foundAtleastOneAttachedMessage) { String msgid = mm.getHeader("Message-ID", " "); LOG.warn("message uri=" + msgUri + " message-id=" + msgid + " had no attachments"); } }
From source file:com.mirth.connect.connectors.http.HttpMessageConverter.java
private static void processContent(DonkeyElement contentElement, Object content, ContentType contentType, boolean parseMultipart, BinaryContentTypeResolver resolver) throws DonkeyElementException, MessagingException, IOException { if (resolver == null) { resolver = defaultResolver;/*from ww w . j a v a2 s .co m*/ } if (parseMultipart && content instanceof MimeMultipart) { contentElement.setAttribute("multipart", "yes"); MimeMultipart multipart = (MimeMultipart) content; String boundary = contentType.getParameter("boundary"); if (StringUtils.isNotBlank(boundary)) { contentElement.setAttribute("boundary", boundary); } if (StringUtils.isNotEmpty(multipart.getPreamble())) { contentElement.addChildElement("Preamble", multipart.getPreamble()); } for (int partIndex = 0; partIndex < multipart.getCount(); partIndex++) { BodyPart part = multipart.getBodyPart(partIndex); DonkeyElement partElement = contentElement.addChildElement("Part"); DonkeyElement headersElement = partElement.addChildElement("Headers"); ContentType partContentType = contentType; for (Enumeration<javax.mail.Header> en = part.getAllHeaders(); en.hasMoreElements();) { javax.mail.Header header = en.nextElement(); headersElement.addChildElement(header.getName(), header.getValue()); if (header.getName().equalsIgnoreCase("Content-Type")) { try { partContentType = ContentType.parse(header.getValue()); } catch (RuntimeException e) { } } } processContent(partElement.addChildElement("Content"), part.getContent(), partContentType, true, resolver); } } else { contentElement.setAttribute("multipart", "no"); String charset = getDefaultHttpCharset( contentType.getCharset() != null ? contentType.getCharset().name() : null); // Call the resolver to determine if the content should be Base64 encoded if (resolver.isBinaryContentType(contentType)) { contentElement.setAttribute("encoding", "Base64"); byte[] contentByteArray = null; if (content instanceof StreamSource) { StreamSource streamSource = (StreamSource) content; if (streamSource.getInputStream() != null) { contentByteArray = IOUtils.toByteArray(streamSource.getInputStream()); } else if (streamSource.getReader() != null) { contentByteArray = IOUtils.toString(streamSource.getReader()).getBytes(charset); } } else if (content instanceof InputStream) { contentByteArray = IOUtils.toByteArray((InputStream) content); } else if (content instanceof byte[]) { contentByteArray = (byte[]) content; } if (contentByteArray == null) { contentByteArray = (content != null ? content.toString() : "").getBytes(charset); } contentElement.setTextContent(new String(Base64Util.encodeBase64(contentByteArray), "US-ASCII")); } else { String contentText = null; if (content instanceof StreamSource) { StreamSource streamSource = (StreamSource) content; if (streamSource.getInputStream() != null) { contentText = IOUtils.toString(streamSource.getInputStream(), charset); } else if (streamSource.getReader() != null) { contentText = IOUtils.toString(streamSource.getReader()); } } else if (content instanceof InputStream) { contentText = IOUtils.toString((InputStream) content, charset); } else if (content instanceof byte[]) { contentText = new String((byte[]) content, charset); } if (contentText == null) { contentText = content != null ? content.toString() : ""; } contentElement.setTextContent(contentText); } } }
From source file:gov.nist.healthcare.ttt.parsing.Parsing.java
public static SOAPWithAttachment parseMtom(String mtom) throws MessagingException, IOException { // Parsing.fixMissingEndBoundry(mtom); MimeMultipart mp; // String contentType = Parsing.findContentType(mtom); // mp = new MimeMultipart(new ByteArrayDataSource(mtom.getBytes(), ""), new ContentType(contentType)); mp = new MimeMultipart(new ByteArrayDataSource(mtom.getBytes(), "multipart/related")); SOAPWithAttachment swa = new SOAPWithAttachment(); int count = mp.getCount(); for (int i = 0; i < count; i++) { BodyPart bp = mp.getBodyPart(i); String contentType = bp.getContentType(); if (contentType.startsWith("application/xop+xml")) { // SOAP ByteArrayInputStream content = (ByteArrayInputStream) bp.getContent(); swa.setSoap(IOUtils.toString(content)); } else {//from w w w. j av a 2 s . co m Object contentRaw = bp.getContent(); if (contentRaw instanceof String) { String content = (String) bp.getContent(); swa.getAttachment().add(content.getBytes()); } else if (contentRaw instanceof SharedByteArrayInputStream) { SharedByteArrayInputStream content = (SharedByteArrayInputStream) bp.getContent(); swa.getAttachment().add(read(content)); } else { System.out.println("UNKNOWN ATTACHMENT TYPE = " + contentRaw.getClass().getName()); swa.getAttachment().add(new String().getBytes()); } } // System.out.println("contentype=" + bp.getContentType()); //ByteArrayInputStream content = (ByteArrayInputStream) bp.getContent(); //String contentString = IOUtils.toString(content); //String contentString = (String) bp.getContent(); /* try { Envelope env = (Envelope) JAXB.unmarshal(new StringReader(contentString), Envelope.class); if (env.getHeader() == null && env.getBody() == null) { swa.getAttachment().add(Parsing.read(content)); //swa.getAttachment().add(contentString.getBytes()); } else { swa.setSoap(contentString); } } catch (Exception saxe) { // Not SOAP so must be attachment. swa.getAttachment().add(Parsing.read(content)); //swa.getAttachment().add(contentString.getBytes()); } */ } if (swa.getAttachment() == null || swa.getAttachment().size() == 0) { byte[] document = Parsing.getDocumentFromSoap(swa.getSoap()).getBytes(); Collection<byte[]> attachments = new ArrayList<byte[]>(); attachments.add(document); swa.setAttachment(attachments); } return swa; }
From source file:com.ctriposs.r2.message.rest.QueryTunnelUtil.java
/** * Takes a Request object that has been encoded for tunnelling as a POST with an X-HTTP-Override-Method header and * creates a new request that represents the intended original request * * @param request the request to be decoded * * @return a decoded RestRequest/* w ww . ja v a 2 s. com*/ */ public static RestRequest decode(final RestRequest request) throws MessagingException, IOException, URISyntaxException { if (request.getHeader(HEADER_METHOD_OVERRIDE) == null) { // Not a tunnelled request, just pass thru return request; } String query = null; byte[] entity = new byte[0]; // All encoded requests must have a content type. If the header is missing, ContentType throws an exception ContentType contentType = new ContentType(request.getHeader(HEADER_CONTENT_TYPE)); RestRequestBuilder requestBuilder = request.builder(); // Get copy of headers and remove the override Map<String, String> h = new HashMap<String, String>(request.getHeaders()); h.remove(HEADER_METHOD_OVERRIDE); // Simple case, just extract query params from entity, append to query, and clear entity if (contentType.getBaseType().equals(FORM_URL_ENCODED)) { query = request.getEntity().asString(Data.UTF_8_CHARSET); h.remove(HEADER_CONTENT_TYPE); h.remove(CONTENT_LENGTH); } else if (contentType.getBaseType().equals(MULTIPART)) { // Clear these in case there is no body part h.remove(HEADER_CONTENT_TYPE); h.remove(CONTENT_LENGTH); MimeMultipart multi = new MimeMultipart(new DataSource() { @Override public InputStream getInputStream() throws IOException { return request.getEntity().asInputStream(); } @Override public OutputStream getOutputStream() throws IOException { return null; } @Override public String getContentType() { return request.getHeader(HEADER_CONTENT_TYPE); } @Override public String getName() { return null; } }); for (int i = 0; i < multi.getCount(); i++) { MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(i); if (part.isMimeType(FORM_URL_ENCODED) && query == null) { // Assume the first segment we come to that is urlencoded is the tunneled query params query = IOUtils.toString((InputStream) part.getContent(), UTF8); } else if (entity.length <= 0) { // Assume the first non-urlencoded content we come to is the intended entity. entity = IOUtils.toByteArray((InputStream) part.getContent()); h.put(CONTENT_LENGTH, Integer.toString(entity.length)); h.put(HEADER_CONTENT_TYPE, part.getContentType()); } else { // If it's not form-urlencoded and we've already found another section, // this has to be be an extra body section, which we have no way to handle. // Proceed with the request as if the 1st part we found was the expected body, // but log a warning in case some client is constructing a request that doesn't // follow the rules. String unexpectedContentType = part.getContentType(); LOG.warn("Unexpected body part in X-HTTP-Method-Override request, type=" + unexpectedContentType); } } } // Based on what we've found, construct the modified request. It's possible that someone has // modified the request URI, adding extra query params for debugging, tracking, etc, so // we have to check and append the original query correctly. if (query != null && query.length() > 0) { String separator = "&"; String existingQuery = request.getURI().getRawQuery(); if (existingQuery == null) { separator = "?"; } else if (existingQuery.isEmpty()) { // This would mean someone has appended a "?" with no args to the url underneath us separator = ""; } requestBuilder.setURI(new URI(request.getURI().toString() + separator + query)); } requestBuilder.setEntity(entity); requestBuilder.setHeaders(h); requestBuilder.setMethod(request.getHeader(HEADER_METHOD_OVERRIDE)); return requestBuilder.build(); }
From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java
/** * Takes a Request object that has been encoded for tunnelling as a POST with an X-HTTP-Override-Method header and * creates a new request that represents the intended original request * * @param request the request to be decoded * @param requestContext a RequestContext object associated with the request * * @return a decoded RestRequest/* w ww .j a v a 2 s. c o m*/ */ public static RestRequest decode(final RestRequest request, RequestContext requestContext) throws MessagingException, IOException, URISyntaxException { if (request.getHeader(HEADER_METHOD_OVERRIDE) == null) { // Not a tunnelled request, just pass thru return request; } String query = null; byte[] entity = new byte[0]; // All encoded requests must have a content type. If the header is missing, ContentType throws an exception ContentType contentType = new ContentType(request.getHeader(HEADER_CONTENT_TYPE)); RestRequestBuilder requestBuilder = request.builder(); // Get copy of headers and remove the override Map<String, String> h = new HashMap<String, String>(request.getHeaders()); h.remove(HEADER_METHOD_OVERRIDE); // Simple case, just extract query params from entity, append to query, and clear entity if (contentType.getBaseType().equals(FORM_URL_ENCODED)) { query = request.getEntity().asString(Data.UTF_8_CHARSET); h.remove(HEADER_CONTENT_TYPE); h.remove(CONTENT_LENGTH); } else if (contentType.getBaseType().equals(MULTIPART)) { // Clear these in case there is no body part h.remove(HEADER_CONTENT_TYPE); h.remove(CONTENT_LENGTH); MimeMultipart multi = new MimeMultipart(new DataSource() { @Override public InputStream getInputStream() throws IOException { return request.getEntity().asInputStream(); } @Override public OutputStream getOutputStream() throws IOException { return null; } @Override public String getContentType() { return request.getHeader(HEADER_CONTENT_TYPE); } @Override public String getName() { return null; } }); for (int i = 0; i < multi.getCount(); i++) { MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(i); if (part.isMimeType(FORM_URL_ENCODED) && query == null) { // Assume the first segment we come to that is urlencoded is the tunneled query params query = IOUtils.toString((InputStream) part.getContent(), UTF8); } else if (entity.length <= 0) { // Assume the first non-urlencoded content we come to is the intended entity. Object content = part.getContent(); if (content instanceof MimeMultipart) { ByteArrayOutputStream os = new ByteArrayOutputStream(); ((MimeMultipart) content).writeTo(os); entity = os.toByteArray(); } else { entity = IOUtils.toByteArray((InputStream) content); } h.put(CONTENT_LENGTH, Integer.toString(entity.length)); h.put(HEADER_CONTENT_TYPE, part.getContentType()); } else { // If it's not form-urlencoded and we've already found another section, // this has to be be an extra body section, which we have no way to handle. // Proceed with the request as if the 1st part we found was the expected body, // but log a warning in case some client is constructing a request that doesn't // follow the rules. String unexpectedContentType = part.getContentType(); LOG.warn("Unexpected body part in X-HTTP-Method-Override request, type=" + unexpectedContentType); } } } // Based on what we've found, construct the modified request. It's possible that someone has // modified the request URI, adding extra query params for debugging, tracking, etc, so // we have to check and append the original query correctly. if (query != null && query.length() > 0) { String separator = "&"; String existingQuery = request.getURI().getRawQuery(); if (existingQuery == null) { separator = "?"; } else if (existingQuery.isEmpty()) { // This would mean someone has appended a "?" with no args to the url underneath us separator = ""; } requestBuilder.setURI(new URI(request.getURI().toString() + separator + query)); } requestBuilder.setEntity(entity); requestBuilder.setHeaders(h); requestBuilder.setMethod(request.getHeader(HEADER_METHOD_OVERRIDE)); requestContext.putLocalAttr(R2Constants.IS_QUERY_TUNNELED, true); return requestBuilder.build(); }