List of usage examples for javax.mail BodyPart getContentType
public String getContentType() throws MessagingException;
From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.MimeMessageResponse.java
public MimeMessageResponse(WsdlRequest wsdlRequest, final TimeablePostMethod postMethod, String requestContent) {/*from w w w .ja v a 2 s. com*/ this.wsdlRequest = wsdlRequest; this.requestContent = requestContent; this.timeTaken = postMethod.getTimeTaken(); responseContentLength = postMethod.getResponseContentLength(); try { initHeaders(postMethod); MimeMultipart mp = new MimeMultipart(new PostResponseDataSource(postMethod)); message = new MimeMessage(HttpClientRequestTransport.JAVAMAIL_SESSION); message.setContent(mp); Header h = postMethod.getResponseHeader("Content-Type"); HeaderElement[] elements = h.getElements(); String rootPartId = null; for (HeaderElement element : elements) { if (element.getName().toUpperCase().startsWith("MULTIPART/")) { NameValuePair parameter = element.getParameterByName("start"); if (parameter != null) rootPartId = parameter.getValue(); } } for (int c = 0; c < mp.getCount(); c++) { BodyPart bodyPart = mp.getBodyPart(c); if (bodyPart.getContentType().toUpperCase().startsWith("MULTIPART/")) { MimeMultipart mp2 = new MimeMultipart(new BodyPartDataSource(bodyPart)); for (int i = 0; i < mp2.getCount(); i++) { result.add(new BodyPartAttachment(mp2.getBodyPart(i))); } } else { BodyPartAttachment attachment = new BodyPartAttachment(bodyPart); String[] contentIdHeaders = bodyPart.getHeader("Content-ID"); if (contentIdHeaders != null && contentIdHeaders.length > 0 && contentIdHeaders[0].equals(rootPartId)) { rootPart = attachment; } else result.add(attachment); } } // if no explicit root part has been set, use the first one in the result if (rootPart == null) rootPart = result.remove(0); if (wsdlRequest.getSettings().getBoolean(HttpSettings.INCLUDE_RESPONSE_IN_TIME_TAKEN)) this.timeTaken = postMethod.getTimeTakenUntilNow(); } catch (Exception e) { e.printStackTrace(); } }
From source file:eu.peppol.as2.MdnMimeMessageInspector.java
/** * Return the fist part which have the given contentType * * @param contentType the mime type to look for *//*ww w . jav a 2 s .co m*/ private BodyPart getPartFromMultipartReport(String contentType) { try { MimeMultipart multipartReport = getMultipartReport(); for (int t = 0; t < multipartReport.getCount(); t++) { BodyPart bp = multipartReport.getBodyPart(t); if (bp.getContentType().contains(contentType)) return bp; } } catch (Exception e) { log.error("Failed to locate part of multipart/report of type " + contentType); } return null; }
From source file:com.seleniumtests.connectors.mails.ImapClient.java
/** * returns message parts// w w w . j a v a 2 s . co m * @param content * @return message parts * @throws IOException * @throws MessagingException */ private List<BodyPart> getMessageParts(Multipart content) throws IOException, MessagingException { List<BodyPart> partList = new ArrayList<>(); for (int partId = 0; partId < content.getCount(); partId++) { BodyPart part = content.getBodyPart(partId); if (part.getContentType().toLowerCase().contains("multipart/")) { partList.addAll(getMessageParts((Multipart) part.getContent())); } else { partList.add(part); } } return partList; }
From source file:com.xebialabs.xlt.ci.server.XLTestServerImplTest.java
private void verifyUploadRequest(final RecordedRequest request) throws IOException, MessagingException { assertEquals(request.getRequestLine(), "POST /api/internal/import/testspecid HTTP/1.1"); assertEquals(request.getHeader("accept"), "application/json; charset=utf-8"); assertEquals(request.getHeader("authorization"), "Basic YWRtaW46YWRtaW4="); assertThat(request.getHeader("Content-Length"), is(nullValue())); assertThat(request.getHeader("Transfer-Encoding"), is("chunked")); assertThat(request.getChunkSizes().get(0), greaterThan(0)); assertThat(request.getChunkSizes().size(), greaterThan(0)); assertTrue(request.getBodySize() > 0); ByteArrayDataSource bads = new ByteArrayDataSource(request.getBody().inputStream(), "multipart/mixed"); MimeMultipart mp = new MimeMultipart(bads); assertTrue(request.getBodySize() > 0); assertEquals(mp.getCount(), 2);// w w w . j av a 2 s. co m assertEquals(mp.getContentType(), "multipart/mixed"); // TODO could do additional checks on metadata content BodyPart bodyPart1 = mp.getBodyPart(0); assertEquals(bodyPart1.getContentType(), "application/json; charset=utf-8"); BodyPart bodyPart2 = mp.getBodyPart(1); assertEquals(bodyPart2.getContentType(), "application/zip"); }
From source file:MultipartViewer.java
protected Component getComponent(BodyPart bp) { try {/*from w w w . j a v a 2s . c o m*/ DataHandler dh = bp.getDataHandler(); CommandInfo ci = dh.getCommand("view"); if (ci == null) { throw new MessagingException("view command failed on: " + bp.getContentType()); } Object bean = dh.getBean(ci); if (bean instanceof Component) { return (Component) bean; } else { if (bean == null) throw new MessagingException( "bean is null, class " + ci.getCommandClass() + " , command " + ci.getCommandName()); else throw new MessagingException("bean is not a awt.Component" + bean.getClass().toString()); } } catch (MessagingException me) { return new Label(me.toString()); } }
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())); }/*from w w w . j a va2 s . c om*/ 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: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 w ww. java 2s .c om*/ 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:com.seleniumtests.connectors.mails.ImapClient.java
/** * get list of all emails in folder//from w w w . j a v a2s .co m * * @param folderName folder to read * @param firstMessageTime date from which we should get messages * @param firstMessageIndex index of the firste message to find * @throws MessagingException * @throws IOException */ @Override public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime) throws MessagingException, IOException { if (folderName == null) { throw new MessagingException("folder ne doit pas tre vide"); } // Get folder Folder folder = store.getFolder(folderName); folder.open(Folder.READ_ONLY); // Get directory Message[] messages = folder.getMessages(); List<Message> preFilteredMessages = new ArrayList<>(); final LocalDateTime firstTime = firstMessageTime; // on filtre les message en fonction du mode de recherche if (searchMode == SearchMode.BY_INDEX || firstTime == null) { for (int i = firstMessageIndex, n = messages.length; i < n; i++) { preFilteredMessages.add(messages[i]); } } else { preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() { private static final long serialVersionUID = 1L; @Override public boolean match(Message msg) { try { return !msg.getReceivedDate() .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant())); } catch (MessagingException e) { return false; } } })); } List<Email> filteredEmails = new ArrayList<>(); lastMessageIndex = messages.length; for (Message message : preFilteredMessages) { String contentType = ""; try { contentType = message.getContentType(); } catch (MessagingException e) { MimeMessage msg = (MimeMessage) message; message = new MimeMessage(msg); contentType = message.getContentType(); } // decode content String messageContent = ""; List<String> attachments = new ArrayList<>(); if (contentType.toLowerCase().contains("text/html")) { messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString()); } else if (contentType.toLowerCase().contains("multipart/")) { List<BodyPart> partList = getMessageParts((Multipart) message.getContent()); // store content in list for (BodyPart part : partList) { String partContentType = part.getContentType().toLowerCase(); if (partContentType.contains("text/html")) { messageContent = messageContent .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString())); } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) { messageContent = messageContent.concat((String) part.getContent().toString()); } else if (partContentType.contains("image") || partContentType.contains("application/") || partContentType.contains("text/x-vcard")) { if (part.getFileName() != null) { attachments.add(part.getFileName()); } else { attachments.add(part.getDescription()); } } else { logger.debug("type: " + part.getContentType()); } } } // create a new email filteredEmails.add(new Email(message.getSubject(), messageContent, "", message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(), attachments)); } folder.close(false); return filteredEmails; }
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); }//w w w.j a v a 2 s. c om 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:se.inera.axel.shs.camel.ShsMessageDataFormatTest.java
@DirtiesContext @Test/* w ww . j a v a 2 s. c o m*/ public void testMarshal() throws Exception { Assert.assertNotNull(testShsMessage); resultEndpoint.expectedMessageCount(1); template.sendBody("direct:marshal", testShsMessage); resultEndpoint.assertIsSatisfied(); List<Exchange> exchanges = resultEndpoint.getReceivedExchanges(); Exchange exchange = exchanges.get(0); InputStream mimeStream = exchange.getIn().getBody(InputStream.class); MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(System.getProperties()), mimeStream); String[] mimeSubject = mimeMessage.getHeader("Subject"); Assert.assertTrue("SHS Message".equalsIgnoreCase(mimeSubject[0]), "Subject is expected to be 'SHS Message' but was " + mimeSubject[0]); Assert.assertNull(mimeMessage.getMessageID()); MimeMultipart multipart = (MimeMultipart) mimeMessage.getContent(); Assert.assertEquals(multipart.getCount(), 2); BodyPart bodyPart = multipart.getBodyPart(1); String content = (String) bodyPart.getContent(); Assert.assertEquals(content, ShsMessageTestObjectMother.DEFAULT_TEST_BODY); String contentType = bodyPart.getContentType(); Assert.assertTrue( StringUtils.contains(contentType, ShsMessageTestObjectMother.DEFAULT_TEST_DATAPART_CONTENTTYPE), "Content type error"); String encodings[] = bodyPart.getHeader("Content-Transfer-Encoding"); Assert.assertNotNull(encodings); Assert.assertEquals(encodings.length, 1); Assert.assertEquals(encodings[0].toUpperCase(), ShsMessageTestObjectMother.DEFAULT_TEST_DATAPART_TRANSFERENCODING.toString().toUpperCase()); mimeMessage.writeTo(System.out); }