diff --git a/src/main/java/io/rocketbase/mail/dto/EmailAddress.java b/src/main/java/io/rocketbase/mail/dto/EmailAddress.java index b5cd2ae..6504097 100644 --- a/src/main/java/io/rocketbase/mail/dto/EmailAddress.java +++ b/src/main/java/io/rocketbase/mail/dto/EmailAddress.java @@ -1,22 +1,42 @@ package io.rocketbase.mail.dto; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; +import lombok.ToString; import org.springframework.util.StringUtils; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@EqualsAndHashCode(of = {"email", "name"}) @Getter @RequiredArgsConstructor public class EmailAddress { private final String email; - private final String name; + private static final Pattern NAME_EMAIL_PATTERN = Pattern.compile("\"([^\"]*)\"\\s*<([^>]*)>"); + private static final Pattern EMAIL_PATTERN = Pattern.compile("<([^>]*)>"); + public EmailAddress(String email) { this.email = email; this.name = null; } + public static EmailAddress parse(String email) { + Matcher emailNameMatcher = NAME_EMAIL_PATTERN.matcher(email); + if (emailNameMatcher.matches()) { + return new EmailAddress(emailNameMatcher.group(2),emailNameMatcher.group(1) ); + } + Matcher emailMatcher = EMAIL_PATTERN.matcher(email); + if (emailMatcher.matches()) { + return new EmailAddress(emailMatcher.group(1) ); + } + throw new IllegalArgumentException("Invalid email address: " + email); + } + public String toRecipient() { if (!StringUtils.isEmpty(name)) { return "\"%s\" <%s>".formatted(name, email); @@ -24,4 +44,9 @@ public String toRecipient() { return "<%s>".formatted(email); } } + + @Override + public String toString() { + return toRecipient(); + } } diff --git a/src/test/java/io/rocketbase/mail/dto/EmailAddressTest.java b/src/test/java/io/rocketbase/mail/dto/EmailAddressTest.java new file mode 100644 index 0000000..55d3508 --- /dev/null +++ b/src/test/java/io/rocketbase/mail/dto/EmailAddressTest.java @@ -0,0 +1,34 @@ +package io.rocketbase.mail.dto; + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.*; + +class EmailAddressTest { + + @Test + void parseSimple() { + EmailAddress email = EmailAddress.parse(""); + assertThat(email, equalTo(new EmailAddress("marten@rocketbase.io"))); + } + + @Test + void parseCombined() { + EmailAddress whiteSpace = EmailAddress.parse("\"Marten Prieß\" "); + EmailAddress without = EmailAddress.parse("\"Marten Prieß\""); + EmailAddress compared = new EmailAddress("marten@rocketbase.io", "Marten Prieß"); + assertThat(whiteSpace, equalTo(compared)); + assertThat(without, equalTo(compared)); + } + + @Test() + void checkFailure() { + try { + EmailAddress error = EmailAddress.parse("\"Marten Prieß\"