List of usage examples for javax.mail BodyPart getHeader
public String[] getHeader(String header_name) throws MessagingException;
From source file:mitm.common.security.smime.SMIMEUtils.java
public static void writeBodyPart(BodyPart bodyPart, OutputStream output, String defaultContentTransferEncoding) throws IOException, MessagingException { if (bodyPart instanceof MimeBodyPart) { MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart; String[] contentTransferEncodings = bodyPart.getHeader("Content-Transfer-Encoding"); String contentTransferEncoding = defaultContentTransferEncoding; if (contentTransferEncodings != null && contentTransferEncodings.length > 0) { contentTransferEncoding = contentTransferEncodings[0]; }//from w ww .j a va2s . co m /* * First try the raw input stream. * If message is created from a stream Javamail will return the raw stream. If * the message is created from 'scratch' getRawInputStream throws a * MessagingException. We will therefore first try the raw version and if * that fails we fallback on writeTo. */ try { InputStream input = mimeBodyPart.getRawInputStream(); Enumeration<?> lines = mimeBodyPart.getAllHeaderLines(); /* step through all header lines */ while (lines.hasMoreElements()) { String header = (String) lines.nextElement(); output.write(MiscStringUtils.toAsciiBytes(header)); output.write(MailUtils.CRLF_BYTES); } output.write(MailUtils.CRLF_BYTES); if (!contentTransferEncoding.equalsIgnoreCase("binary")) { output = new CRLFOutputStream(output); } IOUtils.copy(input, output); output.flush(); } catch (MessagingException e) { /* * Fallback to writeTo */ if (!contentTransferEncoding.equalsIgnoreCase("binary")) { output = new CRLFOutputStream(output); } bodyPart.writeTo(output); output.flush(); } } else { if (!defaultContentTransferEncoding.equalsIgnoreCase("binary")) { output = new CRLFOutputStream(output); } bodyPart.writeTo(output); output.flush(); } }
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); }// w ww.j a va 2s .co m 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: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 ww. j a v a2s . com 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:com.adaptris.core.services.mime.FlattenMimeParts.java
private String generateIfNoContentId(BodyPart p) throws Exception { String result = null;/*w w w . j a va2 s . c o m*/ try { String[] s = Args.notNull(p.getHeader(HEADER_CONTENT_ID), HEADER_CONTENT_ID); result = s[0]; } catch (IllegalArgumentException e) { } return StringUtils.defaultIfEmpty(result, GUID.getUUID()); }
From source file:mitm.application.djigzo.ca.PFXMailBuilder.java
private void replacePFX(MimeMessage message) throws MessagingException { Multipart mp;/* w w w . jav a2 s .c o m*/ try { mp = (Multipart) message.getContent(); } catch (IOException e) { throw new MessagingException("Error getting message content.", e); } BodyPart pfxPart = null; /* * Fallback in case the template does not contain a DjigzoHeader.MARKER */ BodyPart octetStreamPart = null; /* * Try to find the first attachment with X-Djigzo-Marker attachment header which should be the attachment * we should replace (we should replace the content and keep the headers) */ for (int i = 0; i < mp.getCount(); i++) { BodyPart part = mp.getBodyPart(i); if (ArrayUtils.contains(part.getHeader(DjigzoHeader.MARKER), DjigzoHeader.ATTACHMENT_MARKER_VALUE)) { pfxPart = part; break; } /* * Fallback scanning for octet-stream in case the template does not contain a DjigzoHeader.MARKER */ if (part.isMimeType("application/octet-stream")) { octetStreamPart = part; } } if (pfxPart == null) { if (octetStreamPart != null) { logger.info("Marker not found. Using ocet-stream instead."); /* * Use the octet-stream part */ pfxPart = octetStreamPart; } else { throw new MessagingException("Unable to find the attachment part in the template."); } } pfxPart.setDataHandler(new DataHandler(new ByteArrayDataSource(pfx, "application/octet-stream"))); }
From source file:se.inera.axel.shs.camel.ShsMessageDataFormatTest.java
@DirtiesContext @Test/*from w w w. ja va 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); }
From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.MimeMessageResponse.java
public MimeMessageResponse(WsdlRequest wsdlRequest, final TimeablePostMethod postMethod, String requestContent) {/*w w w.j a va 2s . 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
public Map<String, String> getMdnFields() { Map<String, String> ret = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); try {//from w w w .j av a2s. com BodyPart bp = getMessageDispositionNotificationPart(); boolean contentIsBase64Encoded = false; // // look for base64 transfer encoded MDN's (when Content-Transfer-Encoding is present) // // Content-Type: message/disposition-notification // Content-Transfer-Encoding: base64 // // "Content-Transfer-Encoding not used in HTTP transport Because HTTP, unlike SMTP, // does not have an early history involving 7-bit restriction. // There is no need to use the Content Transfer Encodings of MIME." // String[] contentTransferEncodings = bp.getHeader("Content-Transfer-Encoding"); if (contentTransferEncodings != null && contentTransferEncodings.length > 0) { if (contentTransferEncodings.length > 1) log.warn("MDN has multiple Content-Transfer-Encoding, we only try the first one"); String encoding = contentTransferEncodings[0]; if (encoding == null) encoding = ""; encoding = encoding.trim(); log.info("MDN specifies Content-Transfer-Encoding : '" + encoding + "'"); if ("base64".equalsIgnoreCase(encoding)) { contentIsBase64Encoded = true; } } Object content = bp.getContent(); if (content instanceof InputStream) { InputStream contentInputStream = (InputStream) content; if (contentIsBase64Encoded) { log.debug("MDN seems to be base64 encoded, wrapping content stream in Base64 decoding stream"); contentInputStream = new Base64InputStream(contentInputStream); // wrap in base64 decoding stream } BufferedReader r = new BufferedReader(new InputStreamReader(contentInputStream)); while (r.ready()) { String line = r.readLine(); int firstColon = line.indexOf(":"); // "Disposition: ......" if (firstColon > 0) { String key = line.substring(0, firstColon).trim(); // up to : String value = line.substring(firstColon + 1).trim(); // skip : ret.put(key, value); } } } else { throw new Exception("Unsupported MDN content, expected InputStream found @ " + content.toString()); } } catch (Exception e) { throw new IllegalStateException("Unable to retrieve the values from the MDN : " + e.getMessage(), e); } return ret; }
From source file:mitm.application.djigzo.james.mailets.PDFEncrypt.java
private void addEncryptedPDF(MimeMessage message, byte[] pdf) throws MessagingException { /*//from w w w.j a va 2 s. c o m * Find the existing PDF. The expect that the message is a multipart/mixed. */ if (!message.isMimeType("multipart/mixed")) { throw new MessagingException("Content-type should have been multipart/mixed."); } Multipart mp; try { mp = (Multipart) message.getContent(); } catch (IOException e) { throw new MessagingException("Error getting message content.", e); } BodyPart pdfPart = null; /* * Fallback in case the template does not contain a DjigzoHeader.MARKER */ BodyPart fallbackPart = null; for (int i = 0; i < mp.getCount(); i++) { BodyPart part = mp.getBodyPart(i); if (ArrayUtils.contains(part.getHeader(DjigzoHeader.MARKER), DjigzoHeader.ATTACHMENT_MARKER_VALUE)) { pdfPart = part; break; } /* * Fallback scanning for application/pdf in case the template does not contain a DjigzoHeader.MARKER */ if (part.isMimeType("application/pdf")) { fallbackPart = part; } } if (pdfPart == null) { if (fallbackPart != null) { getLogger().info("Marker not found. Using ocet-stream instead."); /* * Use the octet-stream part */ pdfPart = fallbackPart; } else { throw new MessagingException("Unable to find the attachment part in the template."); } } pdfPart.setDataHandler(new DataHandler(new ByteArrayDataSource(pdf, "application/pdf"))); }
From source file:mitm.application.djigzo.james.mailets.SMIMESignTest.java
@Test public void testProtectedHeaders() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SMIMESign mailet = new SMIMESign(); mailetConfig.setInitParameter("protectedHeader", "subject,to,from"); mailet.init(mailetConfig);/* ww w . j a v a 2s. co m*/ MockMail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message.eml")); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("m.brinkers@pobox.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("test@example.com")); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); MailUtils.writeMessage(mail.getMessage(), new File(tempDir, "testProtectedHeaders.eml")); assertEquals(SMIMEHeader.DETACHED_SIGNATURE_TYPE, SMIMEUtils.dissectSigned((Multipart) mail.getMessage().getContent())[1].getContentType()); // check if some headers are signed Multipart mp = (Multipart) mail.getMessage().getContent(); assertEquals(2, mp.getCount()); BodyPart part = mp.getBodyPart(0); // there should be 3 non content-type headers Enumeration<?> e = part.getNonMatchingHeaders(new String[] { "content-type" }); int count = 0; while (e.hasMoreElements()) { e.nextElement(); count++; } assertEquals(3, count); assertEquals("test simple message", StringUtils.join(part.getHeader("subject"), ",")); assertEquals("test@example.com", StringUtils.join(part.getHeader("from"), ",")); assertEquals("test@example.com", StringUtils.join(part.getHeader("to"), ",")); }