/** * Parses metadata stored in a Debian Control File-like format. * * @see <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html#The-DESCRIPTION-file">Description File</a> */ public static Map<String, String> parseDescriptionFile(final InputStream in) { checkNotNull(in); try { LinkedHashMap<String, String> results = new LinkedHashMap<>(); InternetHeaders headers = new InternetHeaders(in); Enumeration headerEnumeration = headers.getAllHeaders(); while (headerEnumeration.hasMoreElements()) { Header header = (Header) headerEnumeration.nextElement(); String name = header.getName(); String value = header.getValue() .replace("\r\n", "\n") .replace("\r", "\n"); // TODO: "should" be ASCII only, otherwise need to know encoding? results.put(name, value); // TODO: Supposedly no duplicates, is this true? } return results; } catch (MessagingException e) { throw new RException(null, e); } }
protected MessageHeaders getHeaders(MimeMessage message) throws MessagingException { Map<String, String> headerMap = new HashMap<>(); // oh wow 2015 and it's untyped and uses Enumeration Enumeration allHeaders = message.getAllHeaders(); while (allHeaders.hasMoreElements()) { Header header = (Header) allHeaders.nextElement(); String headerName = header.getName(); String headerVal = header.getValue(); headerMap.put(headerName, headerVal); } return new MessageHeaders(headerMap); }
@SuppressWarnings("unchecked") private static String createLog(final Message msg) { StringBuilder bldr = new StringBuilder(); Enumeration<Header> allHeaders; try { allHeaders = msg.getAllHeaders(); } catch (MessagingException e) { return null; } while (allHeaders.hasMoreElements()) { Header header = allHeaders.nextElement(); String name = header.getName(); String value = header.getValue(); bldr.append(name); bldr.append(":"); bldr.append(value); bldr.append("\n"); } return StringUtils.truncate(bldr.toString(), LOG_FIELD_WIDTH); }
String getHeaders(final Part part) throws MessagingException { StringBuilder builder = new StringBuilder(); @SuppressWarnings("unchecked") final Enumeration<Header> headers = part.getAllHeaders(); while (headers.hasMoreElements()) { Header next = headers.nextElement(); builder.append(next.getName()); builder.append(": "); builder.append(next.getValue()); builder.append('\n'); if (!headers.hasMoreElements()) { builder.append('\n'); } } return builder.toString(); }
@SuppressWarnings( "unchecked") @PublicAtsApi public List<PackageHeader> getAllHeaders() throws PackageException { try { List<PackageHeader> headers = new ArrayList<PackageHeader>(); Enumeration<Header> messageHeaders = message.getAllHeaders(); while (messageHeaders.hasMoreElements()) { Header messageHeader = messageHeaders.nextElement(); headers.add(new PackageHeader(messageHeader.getName(), messageHeader.getValue())); } return headers; } catch (MessagingException me) { throw new PackageException(me); } }
private String addHeadersTrace( Enumeration<?> headers, String level ) { final String level1 = level; final String level2 = "\t" + level1; final String prefix = getPrefixTrace(level1, "HEADERS START: "); StringBuilder headersString = new StringBuilder(); boolean hasHeaders = headers.hasMoreElements(); if (hasHeaders) { headersString.append(level1 + "HEADERS START:\n"); while (headers.hasMoreElements()) { Header header = (Header) headers.nextElement(); headersString.append(level2 + header.getName() + ": " + normalizeNewLinesTrace(prefix, header.getValue()) + "\n"); } headersString.append(level1 + "HEADERS END:\n"); } return headersString.toString(); }
public static void moveMIMEHeadersToHTTPHeader (@Nonnull final MimeMessage aMimeMsg, @Nonnull final HttpMessage aHttpMsg) throws MessagingException { ValueEnforcer.notNull (aMimeMsg, "MimeMsg"); ValueEnforcer.notNull (aHttpMsg, "HttpMsg"); // Move all mime headers to the HTTP request final Enumeration <Header> aEnum = aMimeMsg.getAllHeaders (); while (aEnum.hasMoreElements ()) { final Header h = aEnum.nextElement (); // Make a single-line HTTP header value! aHttpMsg.addHeader (h.getName (), HttpHeaderMap.getUnifiedValue (h.getValue ())); // Remove from MIME message! aMimeMsg.removeHeader (h.getName ()); } }
public String generateMessageHash(Message message) { LOG.trace("generateMessageHash for msg: {}", message); String uid = null; // create an UID based on message headers on the message, that ought to be unique StringBuilder buffer = new StringBuilder(); try { Enumeration<?> it = message.getAllHeaders(); while (it.hasMoreElements()) { Header header = (Header) it.nextElement(); buffer.append(header.getName()).append("=").append(header.getValue()).append("\n"); } if (buffer.length() > 0) { LOG.trace("Generating UID from the following:\n {}", buffer); uid = UUID.nameUUIDFromBytes(buffer.toString().getBytes()).toString(); } } catch (MessagingException e) { LOG.warn("Cannot read headers from mail message. This exception will be ignored.", e); } return uid; }
protected Map<String, Object> extractHeadersFromMail(Message mailMessage, Exchange exchange) throws MessagingException { Map<String, Object> answer = new HashMap<String, Object>(); Enumeration<?> names = mailMessage.getAllHeaders(); while (names.hasMoreElements()) { Header header = (Header) names.nextElement(); String value = header.getValue(); if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(header.getName(), value, exchange)) { CollectionHelper.appendValue(answer, header.getName(), value); } } return answer; }
@Override @SuppressWarnings("unchecked") public void onSend(SubEthaMessage msg, SendFilterContext ctx) throws MessagingException { try { boolean didSomething = false; for (Part part: msg.getParts()) { if (part.getContentType().startsWith(SubEthaMessage.DETACHMENT_MIME_TYPE)) { Long id = (Long)part.getContent(); String contentType = part.getHeader(SubEthaMessage.HDR_ORIGINAL_CONTENT_TYPE)[0]; // remove all headers for (Enumeration<Header> e = part.getAllHeaders(); e.hasMoreElements();) { Header header = e.nextElement(); part.removeHeader(header.getName()); } String name = MailUtils.getNameFromContentType(contentType); String attachmentUrl = ctx.getList().getUrlBase() + "attachment/" + id + "/" + name ; part.setText("This attachment was left behind at the server:\n " + attachmentUrl + "\n"); part.setDisposition(Part.INLINE); didSomething = true; } } if (didSomething) msg.save(); } catch (IOException ioex) { log.log(Level.FINE,"Error getting message parts", ioex); } }
@Nonnull private static InternetAddress createAddress(final Header header, final String typeOfAddress) { try { return new InternetAddress(header.getValue()); } catch (final AddressException e) { throw new MimeMessageParseException(format(MimeMessageParseException.ERROR_PARSING_ADDRESS, typeOfAddress), e); } }
public void validateCustomHeaders(final Email email, final MimeMessage sentMessage) throws MessagingException, IOException { Map<String, String> customHeaders = email.getCustomHeaders(); List<Header> internetHeaders = (List<Header>) Collections.list(sentMessage.getAllHeaders()); List<String> headerKeys = internetHeaders.stream().map(Header::getName).collect(toList()); assertions.assertThat(headerKeys) .as("Should contains all the headers keys provided at construction time") .containsAll(customHeaders.keySet()); customHeaders.entrySet().stream() .forEach(entry -> { try { assertions.assertThat(sentMessage.getHeader(entry.getKey())).isNotNull().containsExactly(entry.getValue()); } catch (MessagingException e) { } }); }
@SuppressWarnings("unchecked") public PartAssert<P> headers(Matcher<Iterable<? extends Header>> matcher) { try { String message = "headers of ${partName} of message ${messageIndex}"; for (PartWithContext partWithContext : actual) { Part part = partWithContext.getPart(); assertThat(part == null ? null : (Iterable<? extends Header>) list(part.getAllHeaders()), usingContext(message, partWithContext, matcher)); } return this; } catch (MessagingException e) { throw new AssertionError("Failed to get filename of part", e); } }
@Before public void setUp() throws Exception { javaMailJMSStatistics = new JavaMailJMSStatistics(); javaMailJMSStatistics.registerInJMX(); mimeMessage = Mockito.mock(MimeMessage.class); when(mimeMessage.getAllHeaders()).thenReturn(Collections.enumeration(Arrays.asList(new Header("h1", "v1"), new Header("h2", "v2")))); when(mimeMessage.getMessageID()).thenReturn("MessageId"); when(mimeMessage.getSubject()).thenReturn("MessageSubject"); }
private static ListMultimap<String, String> createHeaders(final Message message) throws MessagingException { ListMultimap<String, String> headers = ArrayListMultimap.create(); for (@SuppressWarnings("unchecked") Enumeration<Header> headersEnum = message.getAllHeaders(); headersEnum.hasMoreElements();) { Header header = headersEnum.nextElement(); headers.put(header.getName(), header.getValue()); } return headers; }
/** * @return Header source code of this Article. */ @Override public String getHeaderSource() { if (this.headerSrc != null) { return this.headerSrc; } StringBuilder buf = new StringBuilder(); for (Enumeration<?> en = this.headers.getAllHeaders(); en .hasMoreElements();) { Header entry = (Header) en.nextElement(); String value = entry.getValue().replaceAll("[\r\n]", " "); buf.append(entry.getName()); buf.append(": "); buf.append(MimeUtility.fold(entry.getName().length() + 2, value)); if (en.hasMoreElements()) { buf.append("\r\n"); } } this.headerSrc = buf.toString(); return this.headerSrc; }
@SuppressWarnings("unchecked") public void persistMessageHeaders(NodeRef messageRef, MimeMessage message) { try { Enumeration<Header> headers = message.getAllHeaders(); List<String> messaheHeadersProperties = new ArrayList<String>(); while(headers.hasMoreElements()) { Header header = headers.nextElement(); if (isPersistableHeader(header)) { messaheHeadersProperties.add(header.getName() + ImapModel.MESSAGE_HEADER_TO_PERSIST_SPLITTER + header.getValue()); if (logger.isDebugEnabled()) { logger.debug("[persistHeaders] Persisting Header " + header.getName() + " : " + header.getValue()); } } } Map<QName, Serializable> props = new HashMap<QName, Serializable>(); props.put(ImapModel.PROP_MESSAGE_HEADERS, (Serializable)messaheHeadersProperties); serviceRegistry.getNodeService().addAspect(messageRef, ImapModel.ASPECT_IMAP_MESSAGE_HEADERS, props); } catch(MessagingException me) { } }
private boolean isPersistableHeader(Header header) { for (String headerToPersist : messageHeadersToPersist) { if (headerToPersist.equalsIgnoreCase(header.getName())) { return true; } } return false; }
public Email(String content, Date date, String subject, String from, String to, String cc, List<Header> headers, List<EmailPart> parts) { this.content = content; this.date = date; this.subject = subject; this.from = from; this.to = to; this.cc = cc; this.headers = headers; this.parts = parts; }
/** * 遍历每封邮件的头部部分 * @param message * @throws MessagingException */ private void getMessageHeader(Message message) throws MessagingException { // TODO Auto-generated method stub @SuppressWarnings("unchecked") Enumeration<Header> allHeader=message.getAllHeaders(); for(;allHeader.hasMoreElements();){ Header header=allHeader.nextElement(); System.out.println(header.getName()+":"+header.getValue()); } }
private String getRequestHeaders(Message message) throws MessagingException { StringBuilder sb = new StringBuilder(); @SuppressWarnings("unchecked") // getAllHeaders() is not yet genericised Enumeration<Header> headers = message.getAllHeaders(); // throws ME writeHeaders(headers, sb); return sb.toString(); }
private void writeHeaders(Enumeration<Header> headers, StringBuilder sb) { while (headers.hasMoreElements()) { Header header = headers.nextElement(); sb.append(header.getName()); sb.append(": "); sb.append(header.getValue()); sb.append("\n"); } }
private void writeBodyPart(StringBuilder sb, BodyPart bodyPart) throws MessagingException, IOException { @SuppressWarnings("unchecked") // API not yet generic Enumeration<Header> allHeaders = bodyPart.getAllHeaders(); // throws ME writeHeaders(allHeaders, sb); String disposition = bodyPart.getDisposition(); // throws ME sb.append("\n"); if (Part.ATTACHMENT.equals(disposition)) { sb.append("<attachment content not shown>"); } else { sb.append(bodyPart.getContent()); // throws IOE, ME } sb.append("\n"); }
/** * Prints all message headers in the format <header name>:<header * value>. * * @param headers headers to print. * @throws Exception if headers can not be printed. */ private void printMessageHeaders(Enumeration headers) throws Exception { print(MESSAGE_HEADERS_DELIMITER); while (headers.hasMoreElements()) { Header h = (Header) headers.nextElement(); print(h.getName() + ":" + h.getValue()); } }
@Override @SuppressWarnings("unchecked") public void onInject(SubEthaMessage msg, FilterContext ctx) throws IgnoreException, HoldException, MessagingException { int maxKB = Integer.parseInt(ctx.getArgument(ARG_MAXSIZEINKB).toString()); String msgContent = (String) ctx.getArgument(ARG_MSG); String expandedMsg = ctx.expand(msgContent); boolean changed = false; try { for (Part p: msg.getParts()) { if (p.getContentType().startsWith("text/") && !Part.ATTACHMENT.equals(p.getDisposition())) continue; if (p.getContentType().startsWith("multipart/")) continue; // Hopefully this means it is some sort of binary time if (p.getSize() > (maxKB * 1024)) { if (log.isLoggable(Level.FINE)) log.log(Level.FINE,"Stripping attachement of type: {0}", p.getContentType()); //remove all headers for (Enumeration<Header> e = p.getAllHeaders(); e.hasMoreElements();) { Header header = e.nextElement(); p.removeHeader(header.getName()); } p.setText(expandedMsg); changed = true; } } if (changed) msg.save(); } catch (IOException ioex) { throw new RuntimeException(ioex); } }
private static void parseMimePartTree(@Nonnull final MimePart currentPart, @Nonnull final ParsedMimeMessageComponents parsedComponents) { for (final Header header : retrieveAllHeaders(currentPart)) { parseHeader(header, parsedComponents); } final String disposition = parseDisposition(currentPart); if (isMimeType(currentPart, "text/plain") && parsedComponents.plainContent == null && !Part.ATTACHMENT.equalsIgnoreCase(disposition)) { parsedComponents.plainContent = parseContent(currentPart); } else if (isMimeType(currentPart, "text/html") && parsedComponents.htmlContent == null && !Part.ATTACHMENT.equalsIgnoreCase(disposition)) { parsedComponents.htmlContent = parseContent(currentPart); } else if (isMimeType(currentPart, "multipart/*")) { final Multipart mp = parseContent(currentPart); for (int i = 0, count = countBodyParts(mp); i < count; i++) { parseMimePartTree(getBodyPartAtIndex(mp, i), parsedComponents); } } else { final DataSource ds = createDataSource(currentPart); // If the diposition is not provided, the part should be treated as attachment if (disposition == null || Part.ATTACHMENT.equalsIgnoreCase(disposition)) { parsedComponents.attachmentList.put(parseResourceName(parseContentID(currentPart), parseFileName(currentPart)), ds); } else if (Part.INLINE.equalsIgnoreCase(disposition)) { if (parseContentID(currentPart) != null) { parsedComponents.cidMap.put(parseContentID(currentPart), ds); } else { // contentID missing -> treat as standard attachment parsedComponents.attachmentList.put(parseResourceName(null, parseFileName(currentPart)), ds); } } else { throw new IllegalStateException("invalid attachment type"); } } }
@SuppressWarnings("StatementWithEmptyBody") private static void parseHeader(final Header header, @Nonnull final ParsedMimeMessageComponents parsedComponents) { if (header.getName().equals("Disposition-Notification-To")) { parsedComponents.dispositionNotificationTo = createAddress(header, "Disposition-Notification-To"); } else if (header.getName().equals("Return-Receipt-To")) { parsedComponents.returnReceiptTo = createAddress(header, "Return-Receipt-To"); } else if (header.getName().equals("Return-Path")) { parsedComponents.bounceToAddress = createAddress(header, "Return-Path"); } else if (!HEADERS_TO_IGNORE.contains(header.getName())) { parsedComponents.headers.put(header.getName(), header.getValue()); } else { // header recognized, but not relevant (see #HEADERS_TO_IGNORE) } }
@SuppressWarnings("WeakerAccess") @Nonnull public static List<Header> retrieveAllHeaders(@Nonnull final MimePart part) { try { return Collections.list(part.getAllHeaders()); } catch (final MessagingException e) { throw new MimeMessageParseException(MimeMessageParseException.ERROR_GETTING_ALL_HEADERS, e); } }
private static String formatHeader( Message thisMessage ) throws Exception { Enumeration<Header> E = thisMessage.getAllHeaders(); StringBuilder tmp = new StringBuilder(128); while (E.hasMoreElements()){ Header hdr = E.nextElement(); tmp.append( hdr.getName() ); tmp.append( ": " ); tmp.append( hdr.getValue() ); tmp.append( "\r\n" ); } return tmp.toString(); }
private static CompositeData convert(MessageAndAddresses maa) { if (maa == null) { return null; } try { TabularData addrData = new TabularDataSupport(TAB_ADDR_TYPE); for(Address addr : maa.getAddresses()) { addrData.put(new CompositeDataSupport(ROW_ADDR_TYPE, new String[]{"addressType", "address"}, new Object[]{addr.getType(), addr.toString()})); } TabularData headerData = new TabularDataSupport(TAB_HEADER_TYPE); Enumeration en = maa.getMessage().getAllHeaders(); while (en.hasMoreElements()) { Header header = (Header) en.nextElement(); headerData.put(new CompositeDataSupport(ROW_HEADER_TYPE, new String[]{"header-name", "header-value"}, new Object[]{header.getName(), header.getValue()})); } String error = null; if (maa.getException() != null) { StringWriter sw = new StringWriter(); sw.append(maa.getException().toString()); maa.getException().printStackTrace(new PrintWriter(sw)); sw.flush(); error = sw.toString(); } return new CompositeDataSupport(MAIL_INFO_TYPE, new String[] {"messageId", "date", "subject", "toAddresses", "headers", "errorDescription"}, new Object[]{maa.getMessage().getMessageID(), new Date(maa.getTimestamp()), maa.getMessage().getSubject(), addrData, headerData, error} ); } catch (OpenDataException | MessagingException e) { throw new IllegalArgumentException("cannot convert MessageAndAddresses to CompositeData", e); } }
private Enumeration createCopyOfHeaders(BodyPart part) throws MessagingException { Enumeration headers = part.getAllHeaders(); InternetHeaders internetHeaders = new InternetHeaders(); while (headers.hasMoreElements()) { Header header = (Header) headers.nextElement(); internetHeaders.addHeader(header.getName(), header.getValue()); } return internetHeaders.getAllHeaders(); }
private void copyHeadersToPart(Enumeration headers, BodyPart part) throws MessagingException { while (headers.hasMoreElements()) { Header header = (Header) headers.nextElement(); part.setHeader(header.getName(), header.getValue()); } }
@Override public InputStream getFullContent() throws IOException { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); // The natural way to do this would be to call email.writeTo(stream) and be done with it. // That works unless there is a non-text attachment, which will not be decoded correctly. // It looks like James sends the attachment unharmed in its original encoding // (i.e. Content-Transfer-Encoding: binary), but Thunderbird treats it as 8bit and // changes zero bytes to spaces (0x20). CR/LFs are altered, too. // The ugly workaround is to write out the email one part at a time (if type=multipart), // reencoding binary attachments to base64. stream.write(Util.readBytes(getHeaderContent())); stream.write(CRLF); if (email.isMimeType("multipart/*")) { String contentType = email.getContentType(); String boundary = contentType.substring(contentType.indexOf("boundary=") + "boundary=".length()); if (boundary.startsWith("\"")) boundary = boundary.substring(1); if (boundary.endsWith("\"")) boundary = boundary.substring(0, boundary.length()-1); List<Part> parts = email.getParts(); for (int partIndex=0; partIndex<parts.size(); partIndex++) { Part part = parts.get(partIndex); stream.write("--".getBytes()); stream.write(boundary.getBytes()); stream.write(CRLF); if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { // write headers @SuppressWarnings("unchecked") Enumeration<Header> headers = part.getAllHeaders(); while (headers.hasMoreElements()) { Header header = headers.nextElement(); if ("Content-Transfer-Encoding".equals(header.getName())) stream.write("Content-Transfer-Encoding: base64".getBytes()); else { stream.write(header.getName().getBytes()); stream.write(": ".getBytes()); stream.write(header.getValue().getBytes()); } stream.write(CRLF); } stream.write(CRLF); // write content byte[] contentBytes = Util.readBytes(part.getInputStream()); String base64Str = new String(com.lambdaworks.codec.Base64.encode(contentBytes)); while (base64Str.length() > 78) { stream.write(base64Str.substring(0, 78).getBytes()); stream.write(CRLF); base64Str = base64Str.substring(78); } if (base64Str.length() > 0) { stream.write(base64Str.getBytes()); stream.write(CRLF); } stream.write(CRLF); } else part.writeTo(stream); stream.write(CRLF); } stream.write("--".getBytes()); stream.write(boundary.getBytes()); stream.write("--".getBytes()); } else // not a multipart email, so write the content unaltered stream.write(Util.readBytes(email.getRawInputStream())); stream.write(CRLF); return new ByteArrayInputStream(stream.toByteArray()); } catch (MessagingException e) { throw new IOException(e); } }
private static void dumpHeaders(final Message msg, final File hdrFile) throws FileNotFoundException, MessagingException { PrintStream hdrOs = null; try { hdrOs = new PrintStream(new BufferedOutputStream(new FileOutputStream(hdrFile))); Enumeration<?> headers = msg.getAllHeaders(); while (headers.hasMoreElements()) { Header header = (Header)headers.nextElement(); hdrOs.println(format("%s: %s", header.getName(), header.getValue())); } log.info("written headers to {}", hdrFile.getName()); } finally { if (hdrOs != null) try { hdrOs.close(); } catch (Exception e) {} } }
@SuppressLint("NewApi") public static void run_me(ArrayList<String> args) throws MessagingException { //HashMap<String,String> hm=new HashMap<String,String>(); //hm.put("kk","ghhj"); /*for(java.util.Map.Entry<String, String> e: hm.entrySet()){ //System.out.println("Key " + e.getKey()); //System.out.println("Value " + e.getValue()); } */ for(String s:args) { // String s=""; InputStream stream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)); Session ss = Session.getDefaultInstance(new Properties()); MimeMessage mi=new MimeMessage(ss,stream); mi.getAllHeaderLines(); for (Enumeration<Header> e = mi.getAllHeaders(); e.hasMoreElements();) { Header h = e.nextElement(); String name=h.getName(); String value=h.getValue(); System.out.println(value); System.out.println(name); h.getValue(); } System.out.println("String: " + s); // parse(s); System.out.println(); } }