org.apache.james.mime4j.dom.Header Java Examples

The following examples show how to use org.apache.james.mime4j.dom.Header. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MessageStoreImpl.java    From sling-samples with Apache License 2.0 6 votes vote down vote up
static Map<String, Object> getMessagePropertiesFromHeader(Header hdr) {
    Map<String, Object> props = new HashMap<String, Object>();

    parseHeaderToProps(hdr, props);

    // message name
    String name;
    if (hdr.getField("Message-ID") != null) {
        name = hdr.getField("Message-ID").getBody();
        name = name.substring(1, name.length()-1); // remove < and >
    } else {
        name = Integer.toHexString(hdr.getField("Date").hashCode());
    }
    props.put(MessageFieldName.NAME, name);

    return props;
}
 
Example #2
Source File: MessageStoreImplRepositoryTestUtil.java    From sling-samples with Apache License 2.0 6 votes vote down vote up
static String getResourcePath(Message msg, MessageStoreImpl store) {
    final Header hdr = msg.getHeader();
    final String listIdRaw = hdr.getField("List-Id").getBody();
    final String listId = listIdRaw.substring(1, listIdRaw.length()-1); // remove < and >

    String msgId;
    final Field msgIdField = hdr.getField("Message-ID");
    if (msgIdField != null) {
        msgId = msgIdField.getBody();
        msgId = msgId.substring(1, msgId.length()-1);
    } else {
        msgId = Integer.toHexString(hdr.getField("Date").hashCode());
    }
    msgId = makeJcrFriendly(msgId);

    String subject = null;
    final Field subjectField = hdr.getField("Subject");
    if (subjectField != null) {
        subject = subjectField.getBody();
    }

    String threadPath = store.threadKeyGen.getThreadKey(subject);
    String path = store.archivePath + getDomainNodeName(listId) + "/" + getListNodeName(listId) +
            "/" + threadPath + "/" + msgId;
    return path;
}
 
Example #3
Source File: EnvelopeParser.java    From NioImapClient with Apache License 2.0 5 votes vote down vote up
public static Envelope parseHeader(Header header) {
  Map<String, String> envelopeFields = header.getFields().stream()
      .filter(f -> EnvelopeField.NAME_INDEX.containsKey(f.getName().toLowerCase()))
      .collect(Collectors.groupingBy(field -> field.getName().toLowerCase(),
          Collectors.mapping(Field::getBody, Collectors.joining(","))));

  Envelope.Builder envelope = new Envelope.Builder();

  String dateString = envelopeFields.get(EnvelopeField.DATE.getFieldName());
  List<ImapAddress> fromAddress = emailAddressesFromStringList(envelopeFields.get(EnvelopeField.FROM.getFieldName()));
  envelope.setDateString(dateString)
      .setSubject(envelopeFields.get(EnvelopeField.SUBJECT.getFieldName()))
      .setFrom(fromAddress)
      .setSender(emailAddressesFromStringList(envelopeFields.get(EnvelopeField.SENDER.getFieldName()), fromAddress))
      .setReplyTo(emailAddressesFromStringList(envelopeFields.get(EnvelopeField.REPLY_TO.getFieldName()), fromAddress))
      .setTo(emailAddressesFromStringList(envelopeFields.get(EnvelopeField.TO.getFieldName())))
      .setCc(emailAddressesFromStringList(envelopeFields.get(EnvelopeField.CC.getFieldName())))
      .setBcc(emailAddressesFromStringList(envelopeFields.get(EnvelopeField.BCC.getFieldName())))
      .setInReplyTo(envelopeFields.get(EnvelopeField.IN_REPLY_TO.getFieldName()))
      .setMessageId(envelopeFields.get(EnvelopeField.MESSAGE_ID.getFieldName()));

  try {
    if (!Strings.isNullOrEmpty(dateString)) {
      envelope.setDate(parseDate(dateString));
    }
  } catch (DateTimeParseException e) {
    LOGGER.debug("Failed to parse date {}", header.getField("date").getBody(), e);
  }
  return envelope.build();
}
 
Example #4
Source File: ImapClientTest.java    From NioImapClient with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppend() throws Exception {
  Header header = new HeaderImpl();
  header.addField(DefaultFieldParser.parse("Subject: This is the subject"));
  header.addField(DefaultFieldParser.parse("To: [email protected]"));
  header.addField(DefaultFieldParser.parse("From: [email protected]"));
  header.addField(DefaultFieldParser.parse("Date: 10-MAY-1994 00:00:00 -0000 (UTC)"));
  header.addField(DefaultFieldParser.parse("Message-ID: 12345"));

  Envelope envelope = new Envelope.Builder().setDate(ZonedDateTime.of(1994, 5, 10, 0, 0, 0, 0, ZoneId.of("UTC")));

  Body body = BasicBodyFactory.INSTANCE.textBody("This is a test");

  Message message = new MessageImpl();
  message.setBody(body);
  message.setHeader(header);

  ImapMessage imapMessage = new ImapMessage.Builder()
      .setFlags(ImmutableSet.of(StandardMessageFlag.SEEN, StandardMessageFlag.RECENT))
      .setEnvelope(envelope)
      .setBody(message);

  FetchResponse preAppendFetchAll = client.fetch(1, Optional.empty(), FetchDataItemType.UID, FetchDataItemType.FLAGS, FetchDataItemType.ENVELOPE, new BodyPeekFetchDataItem()).get();
  assertThat(preAppendFetchAll.getMessages().size()).isEqualTo(1);

  TaggedResponse appendResponse = client.append(DEFAULT_FOLDER, imapMessage.getFlags(), imapMessage.getEnvelope().getDate(), imapMessage).get();
  assertThat(appendResponse.getCode()).isEqualTo(ResponseCode.OK);
  long uid = Long.parseLong(appendResponse.getMessage().substring(25, 26));

  FetchResponse postAppendFetchAll = client.fetch(1, Optional.empty(), FetchDataItemType.UID, FetchDataItemType.ENVELOPE, new BodyPeekFetchDataItem()).get();
  assertThat(postAppendFetchAll.getMessages().size()).isEqualTo(2);

  FetchResponse postAppendFetchUid = client.uidfetch(uid, Optional.of(uid), FetchDataItemType.UID, FetchDataItemType.ENVELOPE, new BodyPeekFetchDataItem()).get();
  assertThat(postAppendFetchUid.getMessages().size()).isEqualTo(1);
  assertThat(postAppendFetchUid.getMessages().iterator().next().getBody().getSubject()).isEqualToIgnoringCase("This is the subject");
  assertThat(postAppendFetchUid.getMessages().iterator().next().getEnvelope().getMessageId()).isEqualToIgnoringCase("12345");
}
 
Example #5
Source File: MessageStoreImpl.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
private static void parseHeaderToProps(Header hdr, Map<String, Object> props) {
    Set<String> processed = new HashSet<String>();
    for (Field f : hdr.getFields()) {
        String name = f.getName();
        if (!processed.contains(name)) {
            processed.add(name);
            String value = "";
            List<Field> fields = hdr.getFields(name);
            for (Field fl : fields) {
                value += fl.getBody()+FIELD_SEPARATOR;
            }
            props.put(name, value.substring(0, value.length()-FIELD_SEPARATOR.length()));
        }
    }
}
 
Example #6
Source File: EmailVerificationTest.java    From email-mime-parser with Apache License 2.0 5 votes vote down vote up
private void assertGettingHeader(String header)
        throws MimeException, IOException {

    Email email = getParsedSimpleGmail();
    Header parsedHeader = email.getHeader();

    Field from = parsedHeader.getField(header);
    Assert.assertEquals(header, from.getName());
}
 
Example #7
Source File: MessageStoreImpl.java    From sling-samples with Apache License 2.0 4 votes vote down vote up
private void save(ResourceResolver resolver, Message msg) throws IOException, LoginException {
    // apply message processors
    for(MessageProcessor processor : getSortedMessageProcessors()) {
        logger.debug("Calling {}", processor);
        processor.processMessage(msg);
    }

    // into path: archive/domain/list/thread/message
    final Map<String, Object> msgProps = new HashMap<String, Object>();
    final List<BodyPart> attachments = new ArrayList<BodyPart>(); 

    msgProps.put(resourceTypeKey, MailArchiveServerConstants.MESSAGE_RT);

    StringBuilder plainBody = new StringBuilder();
    StringBuilder htmlBody = new StringBuilder();
    Boolean hasBody = false;

    if (!msg.isMultipart()) {
        plainBody = new StringBuilder(getTextPart(msg)); 
    } else {
        Multipart multipart = (Multipart) msg.getBody();
        recursiveMultipartProcessing(multipart, plainBody, htmlBody, hasBody, attachments);
    }

    msgProps.put(PLAIN_BODY, plainBody.toString().replaceAll("\r\n", "\n"));
    if (htmlBody.length() > 0) {
        msgProps.put(HTML_BODY, htmlBody.toString());
    }

    msgProps.putAll(getMessagePropertiesFromHeader(msg.getHeader()));
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new DefaultMessageWriter().writeHeader(msg.getHeader(), baos);
    String origHdr = baos.toString(MailArchiveServerConstants.DEFAULT_ENCODER.charset().name());
    msgProps.put(X_ORIGINAL_HEADER, origHdr);
    
    final Header hdr = msg.getHeader();
    final String listIdRaw = hdr.getField(LIST_ID).getBody();
    final String listId = listIdRaw.substring(1, listIdRaw.length()-1); // remove < and >

    final String list = getListNodeName(listId);
    final String domain = getDomainNodeName(listId);
    final String subject = (String) msgProps.get(SUBJECT);
    final String threadPath = threadKeyGen.getThreadKey(subject);
    final String threadName = removeRe(subject);

    Resource parentResource = assertEachNode(resolver, archivePath, domain, list, threadPath, threadName);

    String msgNodeName = makeJcrFriendly((String) msgProps.get(NAME));
    boolean isMsgNodeCreated = assertResource(resolver, parentResource, msgNodeName, msgProps);
    if (isMsgNodeCreated) {
        Resource msgResource = resolver.getResource(parentResource, msgNodeName);
        for (BodyPart att : attachments) {
            if (!attachmentFilter.isEligible(att)) {
                continue;
            }
            final Map<String, Object> attProps = new HashMap<String, Object>();
            parseHeaderToProps(att.getHeader(), attProps);
            Body body = att.getBody();
            if (body instanceof BinaryBody) {
                attProps.put(CONTENT, ((BinaryBody) body).getInputStream());
            } else if (body instanceof TextBody) {
                attProps.put(CONTENT, ((TextBody) body).getInputStream());
            }

            String attNodeName = Text.escapeIllegalJcrChars(att.getFilename());
            assertResource(resolver, msgResource, attNodeName, attProps);
        }

        updateThread(resolver, parentResource, msgProps);
    }
}
 
Example #8
Source File: Email.java    From email-mime-parser with Apache License 2.0 4 votes vote down vote up
public Header getHeader() {
	return header;
}