org.apache.james.mime4j.message.DefaultMessageWriter Java Examples

The following examples show how to use org.apache.james.mime4j.message.DefaultMessageWriter. 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: MessageParserTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void mdnReportShouldBeConsideredAsAttachmentWhenDispositionContentType() throws Exception {
    Message message = MDN.builder()
        .humanReadableText("A little test")
        .report(MDNReport.builder()
            .dispositionField(Disposition.builder()
                .actionMode(DispositionActionMode.Automatic)
                .sendingMode(DispositionSendingMode.Automatic)
                .type(DispositionType.Processed)
                .build())
            .originalMessageIdField("[email protected]")
            .reportingUserAgentField(ReportingUserAgent.builder().userAgentName("Thunderbird").build())
            .finalRecipientField("[email protected]")
            .originalRecipientField("[email protected]")
            .build())
        .build()
        .asMime4JMessageBuilder()
        .build();

    List<ParsedAttachment> result = testee.retrieveAttachments(new ByteArrayInputStream(DefaultMessageWriter.asBytes(message)));
    assertThat(result).hasSize(1)
        .allMatch(attachment -> attachment.getContentType().equals(ContentType.of("message/disposition-notification; charset=UTF-8")));
}
 
Example #2
Source File: ImapMessageWriterUtils.java    From NioImapClient with Apache License 2.0 5 votes vote down vote up
public static String messageBodyToString(ImapMessage imapMessage) throws UnfetchedFieldException, IOException {
  MessageWriter writer = new DefaultMessageWriter();
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  CRLFOutputStream crlfOutputStream = new CRLFOutputStream(outputStream);

  writer.writeMessage(imapMessage.getBody(), crlfOutputStream);
  return outputStream.toString(imapMessage.getBody().getCharset());
}
 
Example #3
Source File: GetMessageListMethodTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
@Category(CassandraAndElasticSearchCategory.class)
public void getMessageListShouldExcludeMessagesWhenAttachmentFilterDoesntMatch() throws Exception {
    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, ALICE.asString(), "mailbox");
    byte[] attachmentContent = ClassLoaderUtils.getSystemResourceAsByteArray("eml/attachment.pdf");
    Multipart multipart = MultipartBuilder.create("mixed")
            .addBodyPart(BodyPartBuilder.create()
                .setBody(attachmentContent, "application/pdf")
                .setContentDisposition("attachment"))
            .addBodyPart(BodyPartBuilder.create()
                .setBody("The message has a PDF attachment.", "plain", StandardCharsets.UTF_8))
            .build();
    Message message = Message.Builder.of()
            .setBody(multipart)
            .build();
    mailboxProbe.appendMessage(ALICE.asString(), ALICE_MAILBOX,
            new ByteArrayInputStream(DefaultMessageWriter.asBytes(message)), new Date(), false, new Flags());
    await();

    given()
        .header("Authorization", aliceAccessToken.asString())
        .body("[[\"getMessageList\", {\"filter\":{\"attachments\":\"no apple inside\"}}, \"#0\"]]")
    .when()
        .post("/jmap")
    .then()
        .statusCode(200)
        .body(ARGUMENTS + ".messageIds", empty());
}
 
Example #4
Source File: GetMessageListMethodTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
@Category(CassandraAndElasticSearchCategory.class)
public void getMessageListShouldIncludeMessagesWhenAttachmentFilterMatches() throws Exception {
    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, ALICE.asString(), "mailbox");
    byte[] attachmentContent = ClassLoaderUtils.getSystemResourceAsByteArray("eml/attachment.pdf");
    Multipart multipart = MultipartBuilder.create("mixed")
            .addBodyPart(BodyPartBuilder.create()
                .setBody(attachmentContent, "application/pdf")
                .setContentDisposition("attachment"))
            .addBodyPart(BodyPartBuilder.create()
                .setBody("The message has a PDF attachment.", "plain", StandardCharsets.UTF_8))
            .build();
    Message message = Message.Builder.of()
            .setBody(multipart)
            .build();
    ComposedMessageId composedMessageId = mailboxProbe.appendMessage(ALICE.asString(), ALICE_MAILBOX,
            new ByteArrayInputStream(DefaultMessageWriter.asBytes(message)), new Date(), false, new Flags());
    await();

    given()
        .header("Authorization", aliceAccessToken.asString())
        .body("[[\"getMessageList\", {\"filter\":{\"attachments\":\"beautiful banana\"}}, \"#0\"]]")
    .when()
        .post("/jmap")
    .then()
        .statusCode(200)
        .body(ARGUMENTS + ".messageIds", contains(composedMessageId.getMessageId().serialize()));
}
 
Example #5
Source File: MessageAppender.java    From james-project with Apache License 2.0 5 votes vote down vote up
public byte[] asBytes(Message message) throws MailboxException {
    try {
        return DefaultMessageWriter.asBytes(message);
    } catch (IOException e) {
        throw new MailboxException("Could not write message as bytes", e);
    }
}
 
Example #6
Source File: MIMEMessageConverter.java    From james-project with Apache License 2.0 5 votes vote down vote up
public byte[] asBytes(Message message) {
    try {
        return DefaultMessageWriter.asBytes(message);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
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: MDNTest.java    From james-project with Apache License 2.0 4 votes vote down vote up
private String asString(Message message) throws Exception {
    return new String(DefaultMessageWriter.asBytes(message), StandardCharsets.UTF_8);
}
 
Example #9
Source File: MessageManager.java    From james-project with Apache License 2.0 4 votes vote down vote up
public AppendCommand build(Message message) throws IOException {
    return build(DefaultMessageWriter.asBytes(message));
}
 
Example #10
Source File: MessageParser.java    From james-project with Apache License 2.0 4 votes vote down vote up
private byte[] getContent(Body body) throws IOException {
    DefaultMessageWriter messageWriter = new DefaultMessageWriter();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    messageWriter.writeBody(body, out);
    return out.toByteArray();
}
 
Example #11
Source File: MessageSearches.java    From james-project with Apache License 2.0 4 votes vote down vote up
private InputStream textHeaders(MailboxMessage message) throws MimeIOException, IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    new DefaultMessageWriter()
        .writeHeader(buildTextHeaders(message), out);
    return new ByteArrayInputStream(out.toByteArray());
}
 
Example #12
Source File: DsnMailCreator.java    From mireka with Apache License 2.0 4 votes vote down vote up
@Override
public void writeTo(OutputStream out) throws IOException {
    new DefaultMessageWriter().writeMessage(message, out);
}