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

The following examples show how to use org.apache.james.mime4j.dom.Message. 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: ElasticSearchIntegrationTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void termsBetweenElasticSearchAndLuceneLimitDueTuNonAsciiCharsShouldBeTruncated() throws Exception {
    MailboxPath mailboxPath = MailboxPath.forUser(USERNAME, INBOX);
    MailboxSession session = MailboxSessionUtil.create(USERNAME);
    MessageManager messageManager = storeMailboxManager.getMailbox(mailboxPath, session);

    String recipient = "[email protected]";
    ComposedMessageId composedMessageId = messageManager.appendMessage(MessageManager.AppendCommand.from(
        Message.Builder.of()
            .setTo(recipient)
            .setBody(Strings.repeat("0à2345678é", 3200), StandardCharsets.UTF_8)),
        session).getId();

    elasticSearch.awaitForElasticSearch();

    assertThat(messageManager.search(SearchQuery.of(SearchQuery.address(SearchQuery.AddressType.To, recipient)), session))
        .containsExactly(composedMessageId.getUid());
}
 
Example #2
Source File: EnvelopeTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void fromMime4JMessageShouldParseMailboxAddressesWithoutName() throws Exception {
    Message message = toMime4JMessage(
        "From: bob@domain\r\n" +
        "To: alice@domain, <cedric@domain>\r\n" +
        "Cc: dave@domain\r\n" +
        "Bcc: edgard@domain\r\n");

    Envelope envelope = Envelope.fromMime4JMessage(message);

    assertThat(envelope).isEqualTo(
        new Envelope(MaybeSender.of(new MailAddress("bob@domain")),
            ImmutableSet.of(new MailAddress("alice@domain"),
                new MailAddress("cedric@domain"),
                new MailAddress("dave@domain"),
                new MailAddress("edgard@domain"))));
}
 
Example #3
Source File: Mime4jMboxParserImplTest.java    From sling-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void testMboxParsing() throws IOException {
    Iterator<Message> iter = parser.parse(new FileInputStream(new File(TU.TEST_FOLDER, WRONGBODY_MBOX)));

    boolean fail = true;
    int i = 1;
    while (iter.hasNext()) {
        final Message message = iter.next();
        File bodyFile = new File(TU.TEST_FOLDER, specialPathFromFilePath(WRONGBODY_MBOX, "_bodyOf" + i, "txt"));
        if (bodyFile.exists()) {
            final String actual = getPlainBody(message);
            final String expected = readTextFile(bodyFile);
            assertEquals("Body #"+i, expected, actual);
            fail = false;
        }
        i++;
    }

    if (fail) {
        fail("No file with expected body.");
    }
}
 
Example #4
Source File: CassandraBulkOperationTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
private String appendOneMessageToTrash() {
    ZonedDateTime dateTime = ZonedDateTime.parse("2014-10-30T14:12:00Z");
    try {
        return jmapServer.getProbe(MailboxProbeImpl.class)
            .appendMessage(USERNAME, TRASH_PATH,
                AppendCommand.builder()
                    .build(Message.Builder
                        .of()
                        .setSubject("my test subject")
                        .setBody("testmail", StandardCharsets.UTF_8)
                        .setDate(Date.from(dateTime.toInstant()))))
            .getMessageId()
            .serialize();
    } catch (MailboxException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: MIMEMessageConverterTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void convertToMimeShouldSetEmptyTextBodyWhenProvided() {
    // Given
    MIMEMessageConverter sut = new MIMEMessageConverter(attachmentContentLoader);
    TextBody expected = new BasicBodyFactory().textBody("", StandardCharsets.UTF_8);

    CreationMessage testMessage = CreationMessage.builder()
            .mailboxId("dead-bada55")
            .subject("subject")
            .from(DraftEmailer.builder().name("sender").build())
            .textBody("")
            .build();

    // When
    Message result = sut.convertToMime(new ValueWithId.CreationMessageEntry(
            CreationMessageId.of("user|mailbox|1"), testMessage), ImmutableList.of(), session);

    // Then
    assertThat(result.getBody()).isEqualToComparingOnlyGivenFields(expected, "content", "charset");
    assertThat(result.getMimeType()).isEqualTo("text/plain");
}
 
Example #6
Source File: SendMDNProcessor.java    From james-project with Apache License 2.0 6 votes vote down vote up
private MessageId sendMdn(ValueWithId.MDNCreationEntry MDNCreationEntry, MailboxSession mailboxSession)
        throws MailboxException, IOException, MessagingException, ParseException, MessageNotFoundException, InvalidOriginMessageForMDNException {

    JmapMDN mdn = MDNCreationEntry.getValue();
    Message originalMessage = retrieveOriginalMessage(mdn, mailboxSession);

    Message mdnAnswer = mdn.generateMDNMessage(originalMessage, mailboxSession);

    Flags seen = new Flags(Flags.Flag.SEEN);
    MetaDataWithContent metaDataWithContent = messageAppender.appendMessageInMailbox(mdnAnswer,
        getOutbox(mailboxSession), seen, mailboxSession);

    messageSender.sendMessage(metaDataWithContent,
        Envelope.fromMime4JMessage(mdnAnswer), mailboxSession);

    return metaDataWithContent.getMessageId();
}
 
Example #7
Source File: MIMEMessageConverterTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void convertToMimeShouldFilterGeneratedHeadersRegardlessOfCaseWhenProvided() {
    // Given
    MIMEMessageConverter sut = new MIMEMessageConverter(attachmentContentLoader);

    String joesEmail = "[email protected]";
    CreationMessage messageHavingInReplyTo = CreationMessage.builder()
            .from(DraftEmailer.builder().email(joesEmail).name("joe").build())
            .headers(ImmutableMap.of("frOM", "[email protected]", "VALID", "valid header value"))
            .mailboxIds(ImmutableList.of("dead-beef-1337"))
            .subject("subject")
            .build();

    // When
    Message result = sut.convertToMime(new ValueWithId.CreationMessageEntry(
            CreationMessageId.of("user|mailbox|1"), messageHavingInReplyTo), ImmutableList.of(), session);

    // Then
    assertThat(result.getFrom()).extracting(Mailbox::getAddress)
        .allMatch(f -> f.equals(joesEmail));
    assertThat(result.getHeader().getFields("VALID")).extracting(Field::getBody)
        .containsOnly("valid header value");
    assertThat(result.getHeader().getFields("From")).extracting(Field::getBody)
        .containsOnly("joe <[email protected]>");
}
 
Example #8
Source File: MIMEMessageConverterTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void convertToMimeShouldSetTextBodyWhenProvided() {
    // Given
    MIMEMessageConverter sut = new MIMEMessageConverter(attachmentContentLoader);
    TextBody expected = new BasicBodyFactory().textBody("Hello all!", StandardCharsets.UTF_8);

    CreationMessage testMessage = CreationMessage.builder()
            .mailboxId("dead-bada55")
            .subject("subject")
            .from(DraftEmailer.builder().name("sender").build())
            .textBody("Hello all!")
            .build();

    // When
    Message result = sut.convertToMime(new ValueWithId.CreationMessageEntry(
            CreationMessageId.of("user|mailbox|1"), testMessage), ImmutableList.of(), session);

    // Then
    assertThat(result.getBody()).isEqualToComparingOnlyGivenFields(expected, "content", "charset");
}
 
Example #9
Source File: MessageFastViewFactory.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<MessageFastView> fromMessageResults(Collection<MessageResult> messageResults) {
    Helpers.assertOneMessageId(messageResults);
    MessageResult firstMessageResult = messageResults.iterator().next();
    Preconditions.checkArgument(fastProjections.containsKey(firstMessageResult.getMessageId()),
        "FromMessageResultAndPreview usage requires a precomputed preview");

    return Mono.fromCallable(() -> {
        MessageFastViewPrecomputedProperties messageProjection = fastProjections.get(firstMessageResult.getMessageId());
        List<MailboxId> mailboxIds = Helpers.getMailboxIds(messageResults);

        Message mimeMessage = Helpers.parse(firstMessageResult.getFullContent().getInputStream());

        return instanciateFastView(messageResults, firstMessageResult, messageProjection, mailboxIds, mimeMessage);
    });
}
 
Example #10
Source File: JmapMDNTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
public void generateMDNMessageShouldUseDispositionHeaders() throws Exception {
    String senderAddress = "sender@local";
    Message originMessage = Message.Builder.of()
        .setMessageId("[email protected]")
        .setFrom(senderAddress)
        .setBody("body", StandardCharsets.UTF_8)
        .addField(new RawField(JmapMDN.RETURN_PATH, "<" + senderAddress + ">"))
        .addField(new RawField(JmapMDN.DISPOSITION_NOTIFICATION_TO, "<" + senderAddress + ">"))
        .build();

    assertThat(
        MDN.generateMDNMessage(originMessage, MAILBOX_SESSION)
            .getTo())
        .extracting(address -> (Mailbox) address)
        .extracting(Mailbox::getAddress)
        .containsExactly(senderAddress);
}
 
Example #11
Source File: MessageContentExtractorTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void extractShouldRetrieveTextBodyAndHtmlBodyWhenTextBodyInMainMultipartAndHtmlBodyInInnerMultipart() throws IOException {
    BodyPart multipartRelated = BodyPartBuilder.create()
            .setBody(MultipartBuilder.create("related")
                    .addBodyPart(htmlPart)
                    .addBodyPart(inlineImage)
                    .build())
            .build();

    Multipart multipartAlternative = MultipartBuilder.create("alternative")
            .addBodyPart(textPart)
            .addBodyPart(multipartRelated)
            .build();

    Message message = Message.Builder.of()
            .setBody(multipartAlternative)
            .build();

    MessageContent actual = testee.extract(message);
    assertThat(actual.getTextBody()).contains(TEXT_CONTENT);
    assertThat(actual.getHtmlBody()).contains(HTML_CONTENT);
}
 
Example #12
Source File: MIMEMessageConverterTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void convertToMimeShouldFilterWhiteSpacesOnlyHeaderNames() {
    // Given
    MIMEMessageConverter sut = new MIMEMessageConverter(attachmentContentLoader);

    CreationMessage messageHavingInReplyTo = CreationMessage.builder()
            .from(DraftEmailer.builder().name("joe").build())
            .headers(ImmutableMap.of("   ", "only spaces header name values"))
            .mailboxIds(ImmutableList.of("dead-beef-1337"))
            .subject("subject")
            .build();

    // When
    Message result = sut.convertToMime(new ValueWithId.CreationMessageEntry(
            CreationMessageId.of("user|mailbox|1"), messageHavingInReplyTo), ImmutableList.of(), session);

    // Then
    assertThat(result.getHeader().getFields("   ")).isEmpty();
    assertThat(result.getHeader().getFields("")).isEmpty();
}
 
Example #13
Source File: MessageContentExtractorTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void extractShouldRetrieveTextAndHtmlBodyWhenOneInlinedTextAttachmentAndMainContentInMultipart() throws IOException {
    BodyPart multipartAlternative = BodyPartBuilder.create()
            .setBody(MultipartBuilder.create("alternative")
                    .addBodyPart(textPart)
                    .addBodyPart(htmlPart)
                    .build())
            .build();

    Multipart multipartMixed = MultipartBuilder.create("mixed")
            .addBodyPart(multipartAlternative)
            .addBodyPart(inlineText)
            .build();

    Message message = Message.Builder.of()
            .setBody(multipartMixed)
            .build();

    MessageContent actual = testee.extract(message);
    assertThat(actual.getTextBody()).contains(TEXT_CONTENT);
    assertThat(actual.getHtmlBody()).contains(HTML_CONTENT);
}
 
Example #14
Source File: MIMEMessageConverterTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void convertToMimeShouldAddMultivaluedHeadersWhenProvided() {
    // Given
    MIMEMessageConverter sut = new MIMEMessageConverter(attachmentContentLoader);

    CreationMessage messageHavingInReplyTo = CreationMessage.builder()
            .from(DraftEmailer.builder().name("sender").build())
            .headers(ImmutableMap.of("FIRST", "first value\nsecond value"))
            .mailboxIds(ImmutableList.of("dead-beef-1337"))
            .subject("subject")
            .build();

    // When
    Message result = sut.convertToMime(new ValueWithId.CreationMessageEntry(
            CreationMessageId.of("user|mailbox|1"), messageHavingInReplyTo), ImmutableList.of(), session);

    // Then
    assertThat(result.getHeader().getFields("FIRST")).extracting(Field::getBody)
        .containsOnly("first value", "second value");
}
 
Example #15
Source File: MIMEMessageConverterTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void convertToMimeShouldSetCorrectLocalDate() {
    // Given
    MIMEMessageConverter sut = new MIMEMessageConverter(attachmentContentLoader);

    Instant now = Instant.now();
    ZonedDateTime messageDate = ZonedDateTime.ofInstant(now, ZoneId.systemDefault());

    CreationMessage testMessage = CreationMessage.builder()
            .mailboxId("dead-bada55")
            .subject("subject")
            .from(DraftEmailer.builder().name("sender").build())
            .date(messageDate)
            .build();

    // When
    Message result = sut.convertToMime(new ValueWithId.CreationMessageEntry(
            CreationMessageId.of("user|mailbox|1"), testMessage), ImmutableList.of(), session);

    // Then
    assertThat(result.getDate()).isEqualToIgnoringMillis(Date.from(now));
}
 
Example #16
Source File: ElasticSearchIntegrationTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void fieldsExceedingLuceneLimitShouldNotBeIgnored() throws Exception {
    MailboxPath mailboxPath = MailboxPath.forUser(USERNAME, INBOX);
    MailboxSession session = MailboxSessionUtil.create(USERNAME);
    MessageManager messageManager = storeMailboxManager.getMailbox(mailboxPath, session);

    String recipient = "[email protected]";
    ComposedMessageId composedMessageId = messageManager.appendMessage(MessageManager.AppendCommand.from(
        Message.Builder.of()
            .setTo(recipient)
            .setBody(Strings.repeat("0123456789 ", 5000), StandardCharsets.UTF_8)),
        session).getId();

    elasticSearch.awaitForElasticSearch();

    assertThat(messageManager.search(SearchQuery.of(SearchQuery.bodyContains("0123456789")), session))
        .containsExactly(composedMessageId.getUid());
}
 
Example #17
Source File: MessageFullViewFactory.java    From james-project with Apache License 2.0 6 votes vote down vote up
private MessageFullView instanciateMessageFullView(MetaDataWithContent message, Message mimeMessage, Optional<String> htmlBody, Optional<String> textBody, MessageFastViewPrecomputedProperties messageProjection) {
    return MessageFullView.builder()
            .id(message.getMessageId())
            .blobId(BlobId.of(blobManager.toBlobId(message.getMessageId())))
            .threadId(message.getMessageId().serialize())
            .mailboxIds(message.getMailboxIds())
            .inReplyToMessageId(Helpers.getHeaderValue(mimeMessage, "in-reply-to"))
            .keywords(message.getKeywords())
            .subject(Strings.nullToEmpty(mimeMessage.getSubject()).trim())
            .headers(Helpers.toHeaderMap(mimeMessage.getHeader().getFields()))
            .from(Emailer.firstFromMailboxList(mimeMessage.getFrom()))
            .to(Emailer.fromAddressList(mimeMessage.getTo()))
            .cc(Emailer.fromAddressList(mimeMessage.getCc()))
            .bcc(Emailer.fromAddressList(mimeMessage.getBcc()))
            .replyTo(Emailer.fromAddressList(mimeMessage.getReplyTo()))
            .size(message.getSize())
            .date(getDateFromHeaderOrInternalDateOtherwise(mimeMessage, message))
            .textBody(textBody)
            .htmlBody(htmlBody)
            .preview(messageProjection.getPreview())
            .attachments(getAttachments(message.getAttachments()))
            .build();
}
 
Example #18
Source File: ElasticSearchIntegrationTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void fieldsWithTooLongTermShouldStillBeIndexed() throws Exception {
    MailboxPath mailboxPath = MailboxPath.forUser(USERNAME, INBOX);
    MailboxSession session = MailboxSessionUtil.create(USERNAME);
    MessageManager messageManager = storeMailboxManager.getMailbox(mailboxPath, session);

    String recipient = "[email protected]";
    ComposedMessageId composedMessageId = messageManager.appendMessage(MessageManager.AppendCommand.from(
        Message.Builder.of()
            .setTo(recipient)
            .setBody(Strings.repeat("0123456789 ", 5000) + " matchMe", StandardCharsets.UTF_8)),
        session).getId();

    elasticSearch.awaitForElasticSearch();

    assertThat(messageManager.search(SearchQuery.of(SearchQuery.bodyContains("matchMe")), session))
        .containsExactly(composedMessageId.getUid());
}
 
Example #19
Source File: PostDequeueDecoratorTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws Exception {
    InMemoryIntegrationResources resources = InMemoryIntegrationResources.defaultResources();
    mailboxManager = resources.getMailboxManager();

    mockedMailQueueItem = mock(MailQueueItem.class);
    mail = FakeMail.defaultFakeMail();
    when(mockedMailQueueItem.getMail()).thenReturn(mail);
    testee = new PostDequeueDecorator(mockedMailQueueItem, mailboxManager, new InMemoryMessageId.Factory(), 
            resources.getMessageIdManager(), new SystemMailboxesProviderImpl(mailboxManager));

    message = Message.Builder.of()
        .setSubject("test")
        .setBody("testmail", StandardCharsets.UTF_8)
        .build();
}
 
Example #20
Source File: MIMEMessageConverterTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void convertToMimeShouldSetEmptyBodyWhenNoBodyProvided() {
    // Given
    MIMEMessageConverter sut = new MIMEMessageConverter(attachmentContentLoader);
    TextBody expected = new BasicBodyFactory().textBody("", StandardCharsets.UTF_8);

    CreationMessage testMessage = CreationMessage.builder()
            .mailboxId("dead-bada55")
            .subject("subject")
            .from(DraftEmailer.builder().name("sender").build())
            .build();

    // When
    Message result = sut.convertToMime(new ValueWithId.CreationMessageEntry(
            CreationMessageId.of("user|mailbox|1"), testMessage), ImmutableList.of(), session);

    // Then
    assertThat(result.getBody()).isEqualToComparingOnlyGivenFields(expected, "content", "charset");
}
 
Example #21
Source File: MessageContentExtractorTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void extractShouldNotRetrieveHtmlBodyWithOneInlinedHTMLAttachmentWithCid() throws IOException {
    //Given
    BodyPart inlinedHTMLPart = BodyPartBuilder.create()
        .setBody(HTML_CONTENT, "html", StandardCharsets.UTF_8)
        .build();
    HeaderImpl inlinedHeader = new HeaderImpl();
    inlinedHeader.addField(Fields.contentDisposition(MimeMessage.INLINE));
    inlinedHeader.addField(Fields.contentType("text/html; charset=utf-8"));
    inlinedHeader.addField(CONTENT_ID_FIELD);
    inlinedHTMLPart.setHeader(inlinedHeader);
    Multipart multipartAlternative = MultipartBuilder.create("alternative")
        .addBodyPart(inlinedHTMLPart)
        .build();
    Message message = Message.Builder.of()
        .setBody(multipartAlternative)
        .build();

    //When
    MessageContent actual = testee.extract(message);

    //Then
    assertThat(actual.getHtmlBody()).isEmpty();
}
 
Example #22
Source File: MessageParser.java    From james-project with Apache License 2.0 6 votes vote down vote up
public List<ParsedAttachment> retrieveAttachments(InputStream fullContent) throws IOException {
    DefaultMessageBuilder defaultMessageBuilder = new DefaultMessageBuilder();
    defaultMessageBuilder.setMimeEntityConfig(MimeConfig.PERMISSIVE);
    defaultMessageBuilder.setDecodeMonitor(DecodeMonitor.SILENT);
    Message message = defaultMessageBuilder.parseMessage(fullContent);
    Body body = message.getBody();
    try {
        if (isAttachment(message, Context.BODY)) {
            return ImmutableList.of(retrieveAttachment(message));
        }

        if (body instanceof Multipart) {
            Multipart multipartBody = (Multipart) body;
            return listAttachments(multipartBody, Context.fromSubType(multipartBody.getSubType()))
                .collect(Guavate.toImmutableList());
        } else {
            return ImmutableList.of();
        }
    } finally {
        body.dispose();
    }
}
 
Example #23
Source File: MessageContentExtractorTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void extractShouldNotRetrieveTextBodyWithOneInlinedTextAttachmentWithCid() throws IOException {
    //Given
    BodyPart inlinedTextPart = BodyPartBuilder.create()
        .setBody(TEXT_CONTENT, "text", StandardCharsets.UTF_8)
        .build();
    HeaderImpl inlinedHeader = new HeaderImpl();
    inlinedHeader.addField(Fields.contentDisposition(MimeMessage.INLINE));
    inlinedHeader.addField(Fields.contentType("text/plain; charset=utf-8"));
    inlinedHeader.addField(CONTENT_ID_FIELD);
    inlinedTextPart.setHeader(inlinedHeader);
    Multipart multipartAlternative = MultipartBuilder.create("alternative")
        .addBodyPart(inlinedTextPart)
        .build();
    Message message = Message.Builder.of()
        .setBody(multipartAlternative)
        .build();

    //When
    MessageContent actual = testee.extract(message);

    //Then
    assertThat(actual.getTextBody()).isEmpty();
}
 
Example #24
Source File: MessageHeaderViewFactory.java    From james-project with Apache License 2.0 6 votes vote down vote up
private Mono<MessageHeaderView> instanciateHeaderView(Collection<MessageResult> messageResults, MessageResult firstMessageResult,
                                                      List<MailboxId> mailboxIds, Message mimeMessage) {
    return Mono.just(MessageHeaderView.messageHeaderBuilder()
        .id(firstMessageResult.getMessageId())
        .mailboxIds(mailboxIds)
        .blobId(BlobId.of(blobManager.toBlobId(firstMessageResult.getMessageId())))
        .threadId(firstMessageResult.getMessageId().serialize())
        .keywords(Helpers.getKeywords(messageResults))
        .size(firstMessageResult.getSize())
        .inReplyToMessageId(Helpers.getHeaderValue(mimeMessage, "in-reply-to"))
        .subject(Strings.nullToEmpty(mimeMessage.getSubject()).trim())
        .headers(Helpers.toHeaderMap(mimeMessage.getHeader().getFields()))
        .from(Emailer.firstFromMailboxList(mimeMessage.getFrom()))
        .to(Emailer.fromAddressList(mimeMessage.getTo()))
        .cc(Emailer.fromAddressList(mimeMessage.getCc()))
        .bcc(Emailer.fromAddressList(mimeMessage.getBcc()))
        .replyTo(Emailer.fromAddressList(mimeMessage.getReplyTo()))
        .date(Helpers.getDateFromHeaderOrInternalDateOtherwise(mimeMessage, firstMessageResult))
        .build());
}
 
Example #25
Source File: AbstractMessageSearchIndexTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void searchWithPDFAttachmentShouldReturnMailsWhenAttachmentContentMatches() throws Exception {
    assumeTrue(storeMailboxManager.getSupportedSearchCapabilities().contains(MailboxManager.SearchCapabilities.Attachment));
    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 messageWithBeautifulBananaAsPDFAttachment = myFolderMessageManager
        .appendMessage(MessageManager.AppendCommand.from(message), session).getId();
    await();

    SearchQuery searchQuery = SearchQuery.of(SearchQuery.attachmentContains("beautiful banana"));

    assertThat(messageSearchIndex.search(session, mailbox2, searchQuery))
        .containsExactly(messageWithBeautifulBananaAsPDFAttachment.getUid());
}
 
Example #26
Source File: MessageContentExtractorTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void extractShouldReturnHtmlAndTextWhenMultipartAlternativeAndFirstPartIsMultipartRelated() throws IOException {
    BodyPart multipartRelated = BodyPartBuilder.create()
        .setBody(MultipartBuilder.create("related")
                .addBodyPart(htmlPart)
                .build())
        .build();
    Multipart multipartAlternative = MultipartBuilder.create("alternative")
            .addBodyPart(multipartRelated)
            .build();
    Message message = Message.Builder.of()
            .setBody(multipartAlternative)
            .build();
    MessageContent actual = testee.extract(message);
    assertThat(actual.getHtmlBody()).contains(HTML_CONTENT);
}
 
Example #27
Source File: JmapMDN.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Optional<Mailbox> getAddressForHeader(Message originalMessage, String fieldName) {
    return Optional.ofNullable(originalMessage.getHeader()
        .getFields(fieldName))
        .orElse(ImmutableList.of())
        .stream()
        .map(field -> AddressListFieldLenientImpl.PARSER.parse(field, new DecodeMonitor()))
        .findFirst()
        .map(AddressListField::getAddressList)
        .map(AddressList::flatten)
        .map(MailboxList::stream)
        .orElse(Stream.of())
        .findFirst();
}
 
Example #28
Source File: MailboxManagerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
    setupMockForPreDeletionHooks();
    this.mailboxManager = provideMailboxManager();

    this.message = Message.Builder.of()
        .setSubject("test")
        .setBody("testmail", StandardCharsets.UTF_8);
}
 
Example #29
Source File: EnvelopeTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void fromMime4JMessageShouldNotThrowOnMissingToHeader() throws Exception {
    Message message = toMime4JMessage(
        "From: bob@domain\r\n" +
        "Cc: dave@domain\r\n" +
        "Bcc: edgard@domain\r\n");

    Envelope envelope = Envelope.fromMime4JMessage(message);

    assertThat(envelope).isEqualTo(
        new Envelope(MaybeSender.of(new MailAddress("bob@domain")),
            ImmutableSet.of(new MailAddress("dave@domain"),
                new MailAddress("edgard@domain"))));
}
 
Example #30
Source File: SendMDNProcessor.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Message retrieveOriginalMessage(JmapMDN mdn, MailboxSession mailboxSession) throws MailboxException, IOException, MessageNotFoundException {
    List<MessageResult> messages = messageIdManager.getMessage(mdn.getMessageId(), FetchGroup.HEADERS, mailboxSession);

    if (messages.size() == 0) {
        throw new MessageNotFoundException();
    }

    DefaultMessageBuilder messageBuilder = new DefaultMessageBuilder();
    messageBuilder.setMimeEntityConfig(MimeConfig.PERMISSIVE);
    messageBuilder.setDecodeMonitor(DecodeMonitor.SILENT);
    return messageBuilder.parseMessage(messages.get(0).getHeaders().getInputStream());
}