org.apache.james.mime4j.dom.address.Mailbox Java Examples

The following examples show how to use org.apache.james.mime4j.dom.address.Mailbox. 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: MIMEMessageConverterTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void convertToMimeShouldFilterGeneratedHeadersWhenProvided() {
    // 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 #2
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 #3
Source File: EnvelopeBuilder.java    From james-project with Apache License 2.0 6 votes vote down vote up
private FetchResponse.Envelope.Address buildMailboxAddress(org.apache.james.mime4j.dom.address.Mailbox mailbox) {
    // Encode the mailbox name
    // See IMAP-266
    String name = mailbox.getName();
    if (name != null) {
        name = EncoderUtil.encodeAddressDisplayName(name);
    }

    final String domain = mailbox.getDomain();
    final DomainList route = mailbox.getRoute();
    final String atDomainList;
    if (route == null || route.size() == 0) {
        atDomainList = null;
    } else {
        atDomainList = route.toRouteString();
    }
    final String localPart = mailbox.getLocalPart();
    return buildMailboxAddress(name, atDomainList, localPart, domain);
}
 
Example #4
Source File: Envelope.java    From james-project with Apache License 2.0 6 votes vote down vote up
public static Envelope fromMime4JMessage(org.apache.james.mime4j.dom.Message mime4JMessage, ValidationPolicy validationPolicy) {
    MaybeSender sender = Optional.ofNullable(mime4JMessage.getFrom())
        .map(MailboxList::stream)
        .orElse(Stream.empty())
        .findAny()
        .map(Mailbox::getAddress)
        .flatMap(addressAsString -> newMailAddress(validationPolicy, addressAsString))
        .map(MaybeSender::of)
        .orElse(MaybeSender.nullSender());

    Stream<MailAddress> to = emailersToMailAddresses(mime4JMessage.getTo(), validationPolicy);
    Stream<MailAddress> cc = emailersToMailAddresses(mime4JMessage.getCc(), validationPolicy);
    Stream<MailAddress> bcc = emailersToMailAddresses(mime4JMessage.getBcc(), validationPolicy);

    return new Envelope(sender,
        StreamUtils.flatten(Stream.of(to, cc, bcc))
            .collect(Guavate.toImmutableSet()));
}
 
Example #5
Source File: SearchUtil.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * Parse the headerValue and delegate to {@link #getDisplayAddress(Mailbox)}
 * 
 * If no display address is found an empty String is returned
 *
 * @return display
 */
public static String getDisplayAddress(String headerValue) {
    AddressList addressList = LenientAddressParser.DEFAULT.parseAddressList(MimeUtil.unfold(headerValue));
    if (addressList != null && addressList.isEmpty() == false) {
        Address address = addressList.get(0);
        if (address instanceof Mailbox) {
            return getDisplayAddress((Mailbox) address);
        } else if (address instanceof Group) {
            Group group = (Group) address;
            if (group != null) {
                MailboxList mList = group.getMailboxes();
                if (mList != null && mList.isEmpty() == false) {
                    return getDisplayAddress(mList.get(0));
                }
            }
        }
    }
    
    return "";
}
 
Example #6
Source File: MIMEMessageConverterTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void convertToMimeShouldSetBothFromAndSenderHeaders() {
    // Given
    MIMEMessageConverter sut = new MIMEMessageConverter(attachmentContentLoader);

    String joesEmail = "[email protected]";
    CreationMessage testMessage = CreationMessage.builder()
            .mailboxIds(ImmutableList.of("deadbeef-dead-beef-dead-beef"))
            .subject("subject")
            .from(DraftEmailer.builder().email(joesEmail).name("joe").build())
            .build();

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

    // Then
    assertThat(result.getFrom()).extracting(Mailbox::getAddress).allMatch(f -> f.equals(joesEmail));
    assertThat(result.getSender().getAddress()).isEqualTo(joesEmail);
}
 
Example #7
Source File: MessageSearches.java    From james-project with Apache License 2.0 6 votes vote down vote up
private boolean matchesAddress(AddressList addressList, String valueToMatch) {
    for (Address address : addressList) {
        if (address instanceof Mailbox) {
            if (doesMailboxContains((Mailbox) address, valueToMatch)) {
                return true;
            }
        } else if (address instanceof Group) {
            MailboxList mList = ((Group) address).getMailboxes();
            for (Mailbox mailbox : mList) {
                if (doesMailboxContains(mailbox, valueToMatch)) {
                    return true;
                }
            }
        }
    }

    return false;
}
 
Example #8
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 #9
Source File: Emailer.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static Emailer fromMailbox(Mailbox mailbox) {
    return Emailer.builder()
        .name(getNameOrAddress(mailbox))
        .email(mailbox.getAddress())
        .allowInvalid()
        .build();
}
 
Example #10
Source File: UseHeaderRecipients.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Stream<Mailbox> convertAddressToMailboxCollection(Address address) {
    if (address instanceof Mailbox) {
        return ImmutableList.of((Mailbox) address).stream();
    } else if (address instanceof Group) {
        return ImmutableList.copyOf(((Group) address).getMailboxes()).stream();
    }
    return Stream.of();
}
 
Example #11
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 #12
Source File: EmailerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void fromAddressListShouldReturnListOfEmailersContainingAddresses() {
    assertThat(Emailer.fromAddressList(new AddressList(
            new Mailbox("user1", "james.org"),
            new Mailbox("user2", "james.org"))))
        .containsExactly(
            Emailer.builder()
                .name("[email protected]")
                .email("[email protected]")
                .build(),
            Emailer.builder()
                .name("[email protected]")
                .email("[email protected]")
                .build());
}
 
Example #13
Source File: EmailerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void fromAddressListShouldReturnListOfEmailersContainingAddressesWithNames() {
    assertThat(Emailer.fromAddressList(new AddressList(
            new Mailbox("myInbox", "user1", "james.org"),
            new Mailbox("hisInbox", "user2", "james.org"))))
        .containsExactly(
            Emailer.builder()
                .name("myInbox")
                .email("[email protected]")
                .build(),
            Emailer.builder()
                .name("hisInbox")
                .email("[email protected]")
                .build());
}
 
Example #14
Source File: EmailerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void firstFromMailboxListShouldReturnTheFirstAddressInList() {
    assertThat(Emailer.firstFromMailboxList(new MailboxList(
            new Mailbox("user1Inbox", "user1", "james.org"),
            new Mailbox("user2Inbox", "user2", "james.org"))))
        .contains(Emailer.builder()
            .name("user1Inbox")
            .email("[email protected]")
            .build());
}
 
Example #15
Source File: Envelope.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static Stream<MailAddress> emailersToMailAddresses(AddressList addresses, ValidationPolicy validationPolicy) {
    return Optional.ofNullable(addresses)
        .map(AddressList::flatten)
        .map(MailboxList::stream)
        .orElse(Stream.of())
        .map(Mailbox::getAddress)
        .map(addressAsString -> newMailAddress(validationPolicy, addressAsString))
        .flatMap(Optional::stream);
}
 
Example #16
Source File: NameAddr.java    From mireka with Apache License 2.0 5 votes vote down vote up
public Mailbox toMime4jMailbox() {
    int iAt = addressSpec.indexOf('@');
    if (iAt == -1)
        throw new RuntimeException("Invalid address specification: "
                + addressSpec);
    String localPart = addressSpec.substring(0, iAt);
    String domain = addressSpec.substring(iAt + 1);
    return new Mailbox(displayName, localPart, domain);
}
 
Example #17
Source File: DsnMailCreator.java    From mireka with Apache License 2.0 5 votes vote down vote up
private Mailbox reversePathToMime4jMailbox(ReversePath reversePath) {
    try {
        return AddressBuilder.DEFAULT.parseMailbox(reversePath
                .getSmtpText());
    } catch (ParseException e) {
        // impossible
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: NameAddrTest.java    From mireka with Apache License 2.0 5 votes vote down vote up
@Test
public final void testToMime4jMailbox() {
    NameAddr nameAddr = new NameAddr("John", "[email protected]");
    Mailbox mailbox = nameAddr.toMime4jMailbox();
    assertEquals("John", mailbox.getName());
    assertEquals("john", mailbox.getLocalPart());
    assertEquals("example.com", mailbox.getDomain());
}
 
Example #19
Source File: MIMEMessageConverter.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Mailbox convertEmailToMimeHeader(DraftEmailer address) {
    if (!address.hasValidEmail()) {
        throw new IllegalArgumentException("address");
    }
    CreationMessage.EmailUserAndDomain emailUserAndDomain = address.getEmailUserAndDomain();
    return new Mailbox(address.getName().orElse(null), null, emailUserAndDomain.getUser().orElse(null), emailUserAndDomain.getDomain().orElse(null));
}
 
Example #20
Source File: MIMEMessageConverter.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void buildMimeHeaders(Message.Builder messageBuilder, CreationMessage newMessage, ImmutableList<MessageAttachmentMetadata> messageAttachments) {
    Optional<Mailbox> fromAddress = newMessage.getFrom().filter(DraftEmailer::hasValidEmail).map(this::convertEmailToMimeHeader);
    fromAddress.ifPresent(messageBuilder::setFrom);
    fromAddress.ifPresent(messageBuilder::setSender);

    messageBuilder.setReplyTo(newMessage.getReplyTo().stream()
            .map(this::convertEmailToMimeHeader)
            .collect(Collectors.toList()));
    messageBuilder.setTo(newMessage.getTo().stream()
            .filter(DraftEmailer::hasValidEmail)
            .map(this::convertEmailToMimeHeader)
            .collect(Collectors.toList()));
    messageBuilder.setCc(newMessage.getCc().stream()
            .filter(DraftEmailer::hasValidEmail)
            .map(this::convertEmailToMimeHeader)
            .collect(Collectors.toList()));
    messageBuilder.setBcc(newMessage.getBcc().stream()
            .filter(DraftEmailer::hasValidEmail)
            .map(this::convertEmailToMimeHeader)
            .collect(Collectors.toList()));
    messageBuilder.setSubject(newMessage.getSubject());
    messageBuilder.setMessageId(generateUniqueMessageId(fromAddress));

    // note that date conversion probably lose milliseconds!
    messageBuilder.setDate(Date.from(newMessage.getDate().toInstant()), TimeZone.getTimeZone(newMessage.getDate().getZone()));
    newMessage.getInReplyToMessageId()
        .ifPresent(id -> addHeader(messageBuilder, IN_REPLY_TO_HEADER, id));
    if (!isMultipart(newMessage, messageAttachments)) {
        newMessage.getHtmlBody().ifPresent(x -> messageBuilder.setContentType(HTML_MEDIA_TYPE, UTF_8_CHARSET));
    }
    newMessage.getHeaders().entrySet().stream()
        .filter(header -> ! header.getKey().trim().isEmpty())
        .filter(header -> ! LOWERCASED_COMPUTED_HEADERS.contains(header.getKey().toLowerCase(Locale.ENGLISH)))
        .forEach(header -> addMultivaluedHeader(messageBuilder, header.getKey(), header.getValue()));
}
 
Example #21
Source File: HeaderCollection.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Stream<Mailbox> convertAddressToMailboxStream(Address address) {
    if (address instanceof Mailbox) {
        return Stream.of((Mailbox) address);
    } else if (address instanceof Group) {
        return ((Group) address).getMailboxes().stream();
    }
    return Stream.empty();
}
 
Example #22
Source File: DeletedMessageConverter.java    From james-project with Apache License 2.0 5 votes vote down vote up
private MaybeSender retrieveSender(Optional<Message> mimeMessage) {
    return mimeMessage
        .map(Message::getSender)
        .map(Mailbox::getAddress)
        .map(MaybeSender::getMailSender)
        .orElse(MaybeSender.nullSender());
}
 
Example #23
Source File: EnvelopeBuilder.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void addAddresses(Group group, List<FetchResponse.Envelope.Address> addresses) {
    final String groupName = group.getName();
    final FetchResponse.Envelope.Address start = startGroup(groupName);
    addresses.add(start);
    final MailboxList mailboxList = group.getMailboxes();
    for (Mailbox mailbox : mailboxList) {
        final FetchResponse.Envelope.Address address = buildMailboxAddress(mailbox);
        addresses.add(address);
    }
    final FetchResponse.Envelope.Address end = endGroup();
    addresses.add(end);
}
 
Example #24
Source File: ICALToJsonAttribute.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Stream<Mailbox> convertAddressToMailboxStream(org.apache.james.mime4j.dom.address.Address address) {
    if (address instanceof Mailbox) {
        return Stream.of((Mailbox) address);
    } else if (address instanceof Group) {
        return ((Group) address).getMailboxes().stream();
    }
    return Stream.empty();
}
 
Example #25
Source File: ICALToJsonAttribute.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Stream<MailAddress> convertMailboxToMailAddress(Mailbox mailbox) {
    try {
        return Stream.of(new MailAddress(mailbox.getAddress()));
    } catch (AddressException e) {
        return Stream.empty();
    }
}
 
Example #26
Source File: UseHeaderRecipients.java    From james-project with Apache License 2.0 5 votes vote down vote up
private MailAddress toMailAddress(Mailbox mailbox) {
    try {
        return new MailAddress(mailbox.getAddress());
    } catch (AddressException e) {
        throw new RuntimeException(e);
    }
}
 
Example #27
Source File: Emailer.java    From james-project with Apache License 2.0 4 votes vote down vote up
private static String getNameOrAddress(Mailbox mailbox) {
    return Optional.ofNullable(mailbox.getName())
        .orElseGet(mailbox::getAddress);
}
 
Example #28
Source File: MIMEMessageConverter.java    From james-project with Apache License 2.0 4 votes vote down vote up
private String generateUniqueMessageId(Optional<Mailbox> fromAddress) {
    String noDomain = null;
    return MimeUtil.createUniqueMessageId(fromAddress
        .map(Mailbox::getDomain)
        .orElse(noDomain));
}
 
Example #29
Source File: MessageSearches.java    From james-project with Apache License 2.0 4 votes vote down vote up
private String encodeAndUnscramble(Mailbox mailbox) {
    return MimeUtil.unscrambleHeaderValue(
        AddressFormatter.DEFAULT.encode(mailbox));
}
 
Example #30
Source File: MessageSearches.java    From james-project with Apache License 2.0 4 votes vote down vote up
private boolean doesMailboxContains(Mailbox mailbox, String searchedText) {
    String mailboxAsString = encodeAndUnscramble(mailbox);
    return mailboxAsString.toUpperCase(Locale.US)
        .contains(searchedText.toUpperCase(Locale.US));
}