Skip to content

Commit 10d760d

Browse files
committed
improve validation logic for inline attachments
1 parent c9df087 commit 10d760d

1 file changed

Lines changed: 34 additions & 1 deletion

File tree

src/main/java/it/aboutbits/springboot/emailservice/lib/application/EmailParameter.java

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@
1111

1212
import java.io.InputStream;
1313
import java.time.OffsetDateTime;
14+
import java.util.HashSet;
1415
import java.util.List;
1516
import java.util.Objects;
1617
import java.util.Set;
18+
import java.util.regex.Pattern;
1719

1820
@Builder
1921
@NullMarked
@@ -48,12 +50,43 @@ public record Email(
4850
@Valid
4951
Set<Attachment> attachments
5052
) {
53+
// the "cid:" scheme is case-insensitive, the contentId itself is not
54+
private static final Pattern CID_REFERENCE_PATTERN = Pattern.compile(
55+
"cid:([^\\s\"'<>]+)",
56+
Pattern.CASE_INSENSITIVE
57+
);
58+
5159
@AssertTrue(message = "each inline attachment contentId must be referenced in the htmlBody as cid:contentId")
5260
public boolean isInlineAttachmentsValid() {
61+
var contentIds = inlineContentIds();
62+
if (contentIds.isEmpty()) {
63+
return true;
64+
}
65+
66+
if (htmlBody == null) {
67+
return false;
68+
}
69+
70+
var referencedContentIds = new HashSet<String>();
71+
var matcher = CID_REFERENCE_PATTERN.matcher(htmlBody);
72+
while (matcher.find()) {
73+
referencedContentIds.add(matcher.group(1));
74+
}
75+
76+
return referencedContentIds.containsAll(contentIds);
77+
}
78+
79+
@AssertTrue(message = "each inline attachment contentId must be unique")
80+
public boolean isInlineAttachmentContentIdsUnique() {
81+
var contentIds = inlineContentIds();
82+
return contentIds.size() == new HashSet<>(contentIds).size();
83+
}
84+
85+
private List<String> inlineContentIds() {
5386
return attachments.stream()
5487
.map(Attachment::contentId)
5588
.filter(Objects::nonNull)
56-
.allMatch(contentId -> htmlBody.contains("cid:" + contentId));
89+
.toList();
5790
}
5891

5992
@Builder

0 commit comments

Comments
 (0)