@Override public void field(Field parsedField) throws MimeException { String name = parsedField.getName(); String raw = parsedField.getRaw().toString(); Part part = (Part) stack.peek(); part.addRawHeader(name, raw); String fieldImmediateValue = MimeUtility.getHeaderParameter(parsedField.getBody(), null); if ("Content-Type".equalsIgnoreCase(name) && MimeUtility.isMessage(fieldImmediateValue)) { isMessagePart = true; } if ("Content-Disposition".equalsIgnoreCase(name) && "attachment".equalsIgnoreCase(fieldImmediateValue)) { isContentDispositionAttachment = true; } }
/** * Gets the unfolded, unparsed and possibly encoded (see RFC 2047) field * body string. * * @return the unfolded unparsed field body string. */ public String getBody() { return rawField.getBody(); }
/** * Returns the value of the <i>Message-ID</i> header field of this message * or <code>null</code> if it is not present. * * @return the identifier of this message. */ public String getMessageId() { Field field = obtainField(FieldName.MESSAGE_ID); return field != null ? field.getBody() : null; }
/** * Returns the value of the <i>Message-ID</i> header field of this message * or <code>null</code> if it is not present. * * @return the identifier of this message. */ public String getMessageId() { Field field = obtainField(FieldName.MESSAGE_ID); if (field == null) return null; return field.getBody(); }
private boolean checkHeader(final CharBuffer buffer, MimeTokenStream parser) throws IOException { final String value = parser.getField().getBody(); final StringReader reader = new StringReader(value); return isFoundIn(reader, buffer); }
public Builder add(Field field) { Preconditions.checkNotNull(field); String headerName = field.getName().toLowerCase(Locale.US); String sanitizedValue = MimeUtil.unscrambleHeaderValue(field.getBody()); if (!headerName.contains(".")) { headers.put(headerName, sanitizedValue); } handleSpecificHeader(headerName, sanitizedValue); return this; }
@Override public void field(Field rawField) throws MimeException { log.debug("field( {} )", rawField); currentSection.append(rawField.getName() + ": " + rawField.getBody()); currentSection.append("\r\n"); if ("Content-Disposition".equals(rawField.getName())) { String line = rawField.getBody(); int idx = line.indexOf("name=\""); if (idx > 0) { idx += "name=\"".length(); int end = line.indexOf("\"", idx); if (end > 0) { name = line.substring(idx, end); log.debug("Diving into section '{}'", name); } } } if ("Content-Type".equals(rawField.getName())) { int idx = rawField.getBody().indexOf("boundary="); if (idx > 0) { boundary = rawField.getBody().substring( idx + "boundary=".length()); log.debug("Boundary is '{}'", boundary); } } }
protected RawField getRawField() { if (rawField instanceof RawField) { return ((RawField) rawField); } else { return new RawField(rawField.getName(), rawField.getBody()); } }
private String getHeader(org.apache.james.mime4j.dom.Message message, String header) { Field field = message.getHeader().getField(header); if (field == null) { return null; } return field.getBody(); }
/** * Write the specified <code>Field</code> to the specified * <code>OutputStream</code>. * * @param field * the <code>Field</code> to write. * @param out * the OutputStream to write to. * @throws IOException * if an I/O error occurs. */ public void writeField(Field field, OutputStream out) throws IOException { ByteSequence raw = field.getRaw(); if (raw == null) { StringBuilder buf = new StringBuilder(); buf.append(field.getName()); buf.append(": "); String body = field.getBody(); if (body != null) { buf.append(body); } raw = ContentUtil.encode(MimeUtil.fold(buf.toString(), 0)); } writeBytes(raw, out); out.write(CRLF); }
private List readHeaders() throws IOException, MimeException { if(log.isDebugEnabled()){ log.debug("readHeaders"); } checkParserState(parser.next(), EntityState.T_START_HEADER); List headers = new ArrayList(); while (parser.next() == EntityState.T_FIELD) { Field field = parser.getField(); String name = field.getName(); String value = field.getBody(); if (log.isDebugEnabled()){ log.debug("addHeader: (" + name + ") value=(" + value +")"); } headers.add(new Header(name, value)); } checkParserState(parser.next(), EntityState.T_BODY); return headers; }
@Override public void field(Field field) throws MimeException { String fieldValue; if (field instanceof RawField) { // check if we can access the body in the raw form so no unfolding was done under the hood ByteSequence raw = field.getRaw(); int len = raw.length(); int off = ((RawField) field).getDelimiterIdx() + 1; if (len > off + 1 && (raw.byteAt(off) & 0xff) == 0x20) { off++; } fieldValue = ContentUtil.decode(raw, off, len - off); } else { fieldValue = field.getBody(); } if (fieldValue.endsWith("\r\f")) { fieldValue = fieldValue.substring(0,fieldValue.length() - 2); } if (fieldValue.startsWith(" ")) { fieldValue = fieldValue.substring(1); } final ResultHeader resultHeader = new ResultHeader(field.getName(), fieldValue); results.add(resultHeader); } });
private static MimeDescriptorImpl createDescriptor( final MimeTokenStream parser) throws IOException, MimeException { EntityState next = parser.next(); final Collection<MessageResult.Header> headers = new ArrayList<>(); while (next != EntityState.T_BODY && next != EntityState.T_END_OF_STREAM && next != EntityState.T_START_MULTIPART) { if (next == EntityState.T_FIELD) { headers.add(new ResultHeader(parser.getField().getName(), parser .getField().getBody().trim())); } next = parser.next(); } final MimeDescriptorImpl mimeDescriptorImpl; switch (next) { case T_BODY: mimeDescriptorImpl = simplePartDescriptor(parser, headers); break; case T_START_MULTIPART: mimeDescriptorImpl = compositePartDescriptor(parser, headers); break; case T_END_OF_STREAM: throw new MimeException("Premature end of stream"); default: throw new MimeException("Unexpected parse state"); } return mimeDescriptorImpl; }
/** Process a multipart body part */ private boolean processMultipart(JCas jCas, Multipart mp, String sourceUri) throws IOException { boolean doneBody = false; for (Entity e : mp.getBodyParts()) { if (e.getFilename() != null) { // Part has a filename, and is therefore an attachment String extension = FilenameUtils.getExtension(e.getFilename()).toLowerCase(); if (ignoreExtensionsList.contains(extension)) { getMonitor().info("Skipping attachment {}", e.getFilename()); continue; } attachments.put(sourceUri + "/" + e.getFilename(), e.getBody()); } else if (!doneBody) { // Part has no filename, and we've not already processed a part to use as a body processBody(jCas, e.getBody(), sourceUri); // Add metadata for (Field f : e.getParent().getHeader().getFields()) { addMetadata(jCas, f.getName(), f.getBody()); } doneBody = true; } } return doneBody; }
/** Process a multipart body part */ private boolean processMultipart(JCas jCas, Multipart mp, String sourceUri) throws IOException { boolean doneBody = false; for (Entity e : mp.getBodyParts()) { if (e.getFilename() != null) { // Part has a filename, and is therefore an attachment String extension = FilenameUtils.getExtension(e.getFilename()).toLowerCase(); if (ignoreExtensionsList.contains(extension)) { getMonitor().info("Skipping attachment {}", e.getFilename()); continue; } attachments.put(sourceUri + "/" + e.getFilename(), e.getBody()); } else if (!doneBody) { // Part has no filename, and we've not already processed a part to use as a body processBody(jCas, e.getBody(), sourceUri); // Add metadata for (Field f : e.getParent().getHeader().getFields()) { addMetadata(jCas, f.getName(), f.getBody()); } doneBody = true; } } return doneBody; }
/** Process a single body part */ private boolean processBody(JCas jCas, Body body, String sourceUri) throws IOException { if (body instanceof TextBody) { // Process plain text body processTextBody(jCas, (TextBody) body); // Add fields from parent for (Field f : body.getParent().getHeader().getFields()) { addMetadata(jCas, f.getName(), f.getBody()); } // Set up document annotation - this is done by the content extractor in other cases DocumentAnnotation doc = UimaSupport.getDocumentAnnotation(jCas); doc.setSourceUri(sourceUri); doc.setTimestamp(System.currentTimeMillis()); } else if (body instanceof BinaryBody) { processBinaryBody(jCas, (BinaryBody) body, sourceUri); } else if (body instanceof Multipart) { // Multipart message, so recurse Multipart mp = (Multipart) body; return processMultipart(jCas, mp, sourceUri); } else { // No body processed return false; } return true; }
/** Process a single body part */ private boolean processBody(JCas jCas, Body body, String sourceUri) throws IOException { if (body instanceof TextBody) { // Process plain text body processTextBody(jCas, (TextBody) body); // Add fields from parent for (Field f : body.getParent().getHeader().getFields()) { addMetadata(jCas, f.getName(), f.getBody()); } // Set up document annotation - this is done by the content extractor in other cases DocumentAnnotation doc = UimaSupport.getDocumentAnnotation(jCas); doc.setSourceUri(sourceUri); doc.setTimestamp(System.currentTimeMillis()); } else if (body instanceof BinaryBody) { processBinaryBody(jCas, (BinaryBody) body, sourceUri); } else if (body instanceof Multipart) { // Multipart message, so recurse Multipart mp = (Multipart) body; return processMultipart(jCas, mp, sourceUri); } else { // No body processed return false; } return true; }
@Test public void convertToMimeShouldGenerateMessageIdContainingSenderDomain() { // Given MIMEMessageConverter sut = new MIMEMessageConverter(); CreationMessage message = CreationMessage.builder() .from(DraftEmailer.builder().email("email@domain.com").build()) .mailboxIds(ImmutableList.of("dead-beef-1337")) .subject("subject") .build(); // When Message result = sut.convertToMime(new ValueWithId.CreationMessageEntry( CreationMessageId.of("user|mailbox|1"), message), ImmutableList.of()); // Then assertThat(result.getHeader().getFields("Message-ID")).hasSize(1); assertThat(result.getHeader().getFields("Message-ID").get(0).getBody()) .contains("@domain.com"); }
@Test public void convertToMimeShouldSetQuotedPrintableContentTransferEncodingWhenText() { // Given MIMEMessageConverter sut = new MIMEMessageConverter(); CreationMessage testMessage = CreationMessage.builder() .mailboxId("dead-bada55") .subject("subject") .from(DraftEmailer.builder().name("sender").build()) .htmlBody("Hello <b>all</b>!") .build(); // When Message result = sut.convertToMime(new ValueWithId.CreationMessageEntry( CreationMessageId.of("user|mailbox|1"), testMessage), ImmutableList.of()); // Then assertThat(result.getHeader() .getField("Content-Transfer-Encoding") .getBody()) .isEqualTo("quoted-printable"); }