feat(ses): support Content.Simple.Attachments in SESv2 SendEmail (#5190)

* feat(ses): support Content.Simple.Attachments in SESv2 SendEmail

Parse and validate Simple attachments, assemble them into one MIME message
with the relay's encoder, run the content scan over it as for raw sends,
relay them over SMTP, and expose them in the /_aws/ses mailbox as an
Attachments summary plus the base64 MIME message in RawData.

* fix(ses): sort SesService imports and document attachment encoding and RawData recipients

RawData keeps the To and Cc recipients the request named, including any
suppression later kept from delivery, and ContentTransferEncoding is validated
but every attachment part is base64-encoded. Both are now stated in the SES docs.

* fix(ses): reject line breaks in attachment MIME header members

ContentType, ContentDescription and ContentId are written verbatim into the
attachment part's MIME headers, so a CR or LF in any of them added header lines
to that part. They are now refused with BadRequestException by the same rule
MessageHeader.isSafe applies to custom headers. missingHeaderMember now builds
its message through constraintViolation.

* fix(ses): refuse attachments with unsupported file extensions

SES does not accept attachments whose file names end in one of the
extensions listed under "SES unsupported attachment types" in the developer
guide. The content scan now walks the parsed MIME for attachment file names,
from Content-Disposition or the Content-Type name parameter, and both the
Simple-with-attachments and raw send paths refuse such a message with
MessageRejected before anything is recorded.

* refactor(ses): share one MIME part walk between the content scans

hasBlockedAttachment repeated the worklist entityContains already used.
Both now go through anyPart, which walks every part, forwarded messages
and multiparts included, and runs the given check on each.
This commit is contained in:
Salil Chincholikar authored and GitHub committed 2026-10-07 14:22:34 -04:00
1 parent 4eae79d546
commit 74b3cecf78
16 files changed
+1082 -77

No files matched your search

@@ -230,4 +230,44 @@ class SesContentScanTest {
}
return out.toString();
}
@Test
void blockedExtensionsMatchCaseInsensitivelyOnTheLastExtension() {
assertTrue(SesContentScan.isBlockedFileName("setup.exe"));
assertTrue(SesContentScan.isBlockedFileName("RUN.BAT"));
assertTrue(SesContentScan.isBlockedFileName("report.pdf.js"));
assertFalse(SesContentScan.isBlockedFileName("report.pdf"));
assertFalse(SesContentScan.isBlockedFileName("setup.exe.txt"));
assertFalse(SesContentScan.isBlockedFileName("exe"));
assertFalse(SesContentScan.isBlockedFileName(null));
}
@Test
void attachmentNamedByDispositionOrContentTypeIsBlocked() {
assertTrue(SesContentScan.hasBlockedAttachment(SmtpRelay.parseMime(
multipart("Content-Disposition: attachment; filename=\"tool.exe\"\r\n"))));
assertTrue(SesContentScan.hasBlockedAttachment(SmtpRelay.parseMime(
multipart("Content-Type: application/octet-stream; name=\"macro.vbs\"\r\n"))));
assertFalse(SesContentScan.hasBlockedAttachment(SmtpRelay.parseMime(
multipart("Content-Disposition: attachment; filename=\"report.pdf\"\r\n"))));
}
@Test
void blockedAttachmentInsideAForwardedMessageIsFound() {
String inner = new String(multipart("Content-Disposition: attachment; filename=\"x.scr\"\r\n"),
StandardCharsets.US_ASCII);
String outer = "From: a@example.com\r\nTo: b@example.com\r\nSubject: fwd\r\n"
+ "MIME-Version: 1.0\r\nContent-Type: message/rfc822\r\n\r\n" + inner;
assertTrue(SesContentScan.hasBlockedAttachment(
SmtpRelay.parseMime(outer.getBytes(StandardCharsets.US_ASCII))));
}
private static byte[] multipart(String attachmentHeaders) {
String mime = "From: a@example.com\r\nTo: b@example.com\r\nSubject: x\r\n"
+ "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"b\"\r\n\r\n"
+ "--b\r\nContent-Type: text/plain\r\n\r\nsee attachment\r\n"
+ "--b\r\n" + attachmentHeaders + "\r\nAAAA\r\n--b--\r\n";
return mime.getBytes(StandardCharsets.US_ASCII);
}
}
@@ -6,7 +6,9 @@ import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
import io.github.hectorvent.floci.services.ses.model.CustomVerificationEmailTemplate;
import io.github.hectorvent.floci.services.ses.model.EmailContent;
import io.github.hectorvent.floci.services.ses.model.InsightsEvent;
import io.github.hectorvent.floci.services.ses.model.MessageAttachment;
import io.github.hectorvent.floci.services.ses.model.SendEmailRequest;
import io.github.hectorvent.floci.services.ses.model.SentAttachment;
import io.github.hectorvent.floci.services.ses.model.SentEmail;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -16,6 +18,8 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.ArgumentCaptor;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@@ -148,6 +152,66 @@ class SesServiceSmtpTest {
assertEquals(messageId, relayed.messageId());
}
private static MessageAttachment pdfAttachment(byte[] content) {
return new MessageAttachment("report.pdf", content, "application/pdf",
MessageAttachment.Disposition.ATTACHMENT, null, null, null);
}
@Test
void sendEmail_withAttachments_relaysThemAndStoresTheAssembledMessage() {
byte[] pdf = "pdf-bytes".getBytes(StandardCharsets.UTF_8);
String messageId = service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.region("us-east-1")
.content(new EmailContent.Simple("Subject", "text", null, List.of(),
List.of(pdfAttachment(pdf))))
.build());
SmtpRelay.RelayMessage relayed = capturedRelay();
assertEquals(1, relayed.attachments().size());
assertArrayEquals(pdf, relayed.attachments().get(0).rawContent());
SentEmail stored = storedEmail(messageId);
assertFalse(stored.isRaw());
assertEquals(List.of(new SentAttachment("report.pdf", "application/pdf", "ATTACHMENT", null, null,
pdf.length)), stored.getAttachments());
String mime = new String(Base64.getDecoder().decode(stored.getMimeData()), StandardCharsets.UTF_8);
assertTrue(mime.contains("report.pdf"), mime);
}
@Test
void sendEmail_withSignatureInAnAttachment_isRejectedAndNotRelayed() {
String messageId = service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.region("us-east-1")
.content(new EmailContent.Simple("Subject", "clean", null, List.of(),
List.of(pdfAttachment(SesContentScan.signature().getBytes(StandardCharsets.US_ASCII)))))
.build());
SentEmail stored = storedEmail(messageId);
assertEquals("Bad content", stored.getRejectReason());
assertNull(stored.getAttachments());
assertNull(stored.getMimeData());
assertEquals(List.of("SEND", "REJECT"), insightsEventTypes(messageId));
verify(smtpRelay, never()).relay(any());
}
@Test
void sendEmail_withoutAttachments_storesNoAttachmentFields() {
String messageId = service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.region("us-east-1")
.content(new EmailContent.Simple("Subject", "text", null, List.of()))
.build());
SentEmail stored = storedEmail(messageId);
assertNull(stored.getAttachments());
assertNull(stored.getMimeData());
assertNull(capturedRelay().attachments());
}
@Test
void sendEmail_storesAndRelays() {
String messageId = service.sendEmail(SendEmailRequest.builder()
@@ -0,0 +1,354 @@
package io.github.hectorvent.floci.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import org.apache.james.mime4j.dom.Body;
import org.apache.james.mime4j.dom.Entity;
import org.apache.james.mime4j.dom.Message;
import org.apache.james.mime4j.dom.Multipart;
import org.apache.james.mime4j.dom.SingleBody;
import org.apache.james.mime4j.stream.Field;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
/**
* SES V2 SendEmail with {@code Content.Simple.Attachments}: the message is assembled as one MIME
* message, scanned, and captured by the inspection endpoint with its attachments.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesSimpleAttachmentsV2IntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request";
private static final String SENDER = "attach-sender@example.com";
private static final byte[] PDF_BYTES = "%PDF-1.4 fake report \u0000\u0001ÿ".getBytes(StandardCharsets.ISO_8859_1);
private static final byte[] PNG_BYTES = {(byte) 0x89, 'P', 'N', 'G', 0, 1, 2, 3, (byte) 0xfe};
@Test
@Order(1)
void createSender() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"EmailIdentity\": \"" + SENDER + "\"}")
.when().post("/v2/email/identities").then().statusCode(200);
}
@Test
@Order(2)
void simpleSend_withAttachmentAndInlinePart_isCapturedWithBoth() throws IOException {
String messageId = send("""
{"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["to@example.com"], "BccAddresses": ["hidden@example.com"]},
"Content": {"Simple": {
"Subject": {"Data": "With attachments"},
"Body": {"Text": {"Data": "plain body"},
"Html": {"Data": "<p>html body <img src=\\"cid:logo\\"></p>"}},
"Headers": [{"Name": "X-Custom", "Value": "custom-value"}],
"Attachments": [
{"FileName": "report.pdf", "RawContent": "%s", "ContentType": "application/pdf",
"ContentDisposition": "ATTACHMENT", "ContentDescription": "Monthly report"},
{"FileName": "logo.png", "RawContent": "%s", "ContentType": "image/png",
"ContentDisposition": "INLINE", "ContentId": "logo"}
]}}}
""".formatted(SENDER, b64(PDF_BYTES), b64(PNG_BYTES)))
.then().statusCode(200).extract().path("MessageId");
JsonPath captured = given().when().get("/_aws/ses?id=" + messageId)
.then().statusCode(200)
.body("messages", hasSize(1))
.body("messages[0].Subject", equalTo("With attachments"))
.body("messages[0].Body.text_part", equalTo("plain body"))
.body("messages[0].Body.html_part", equalTo("<p>html body <img src=\"cid:logo\"></p>"))
.body("messages[0].Destination.ToAddresses", contains("to@example.com"))
.body("messages[0].Headers.find { it.Name == 'X-Custom' }.Value", equalTo("custom-value"))
.body("messages[0].Attachments", hasSize(2))
.body("messages[0].Attachments[0].FileName", equalTo("report.pdf"))
.body("messages[0].Attachments[0].ContentType", equalTo("application/pdf"))
.body("messages[0].Attachments[0].ContentDisposition", equalTo("ATTACHMENT"))
.body("messages[0].Attachments[0].ContentDescription", equalTo("Monthly report"))
.body("messages[0].Attachments[0]", not(hasKey("ContentId")))
.body("messages[0].Attachments[0].Size", equalTo(PDF_BYTES.length))
.body("messages[0].Attachments[1].FileName", equalTo("logo.png"))
.body("messages[0].Attachments[1].ContentType", equalTo("image/png"))
.body("messages[0].Attachments[1].ContentDisposition", equalTo("INLINE"))
.body("messages[0].Attachments[1].ContentId", equalTo("<logo>"))
.body("messages[0].Attachments[1].Size", equalTo(PNG_BYTES.length))
.body("messages[0].RawData", notNullValue())
.extract().jsonPath();
byte[] mime = Base64.getDecoder().decode(captured.getString("messages[0].RawData"));
String wire = new String(mime, StandardCharsets.UTF_8);
assertTrue(wire.contains("Message-ID: <" + messageId + "@email.amazonses.com>"), wire);
assertTrue(wire.contains("X-Custom: custom-value"), wire);
assertFalse(wire.contains("hidden@example.com"), "Bcc must not appear in the message");
Message message = SmtpRelay.parseMime(mime);
assertNotNull(message);
assertEquals("With attachments", message.getSubject());
List<Entity> leaves = new ArrayList<>();
collectLeaves(message, leaves);
Entity pdf = leafNamed(leaves, "report.pdf");
assertEquals("application/pdf", pdf.getMimeType());
assertEquals("attachment", pdf.getDispositionType());
assertArrayEquals(PDF_BYTES, bytes(pdf));
assertEquals("Monthly report", headerValue(pdf, "Content-Description"));
Entity png = leafNamed(leaves, "logo.png");
assertEquals("image/png", png.getMimeType());
assertEquals("inline", png.getDispositionType());
assertEquals("<logo>", headerValue(png, "Content-ID"));
assertArrayEquals(PNG_BYTES, bytes(png));
assertTrue(leaves.stream().anyMatch(e -> "text/plain".equals(e.getMimeType())
&& new String(bytesUnchecked(e), StandardCharsets.UTF_8).contains("plain body")));
assertTrue(leaves.stream().anyMatch(e -> "text/html".equals(e.getMimeType())
&& new String(bytesUnchecked(e), StandardCharsets.UTF_8).contains("cid:logo")));
}
@Test
@Order(3)
void simpleSend_withoutAttachments_isCapturedAsBefore() {
String messageId = send("""
{"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["to@example.com"]},
"Content": {"Simple": {
"Subject": {"Data": "No attachments"},
"Body": {"Text": {"Data": "just text"}}}}}
""".formatted(SENDER))
.then().statusCode(200).extract().path("MessageId");
given().when().get("/_aws/ses?id=" + messageId)
.then().statusCode(200)
.body("messages[0].Subject", equalTo("No attachments"))
.body("messages[0].Body.text_part", equalTo("just text"))
.body("messages[0].Body.html_part", nullValue())
.body("messages[0]", not(hasKey("Attachments")))
.body("messages[0]", not(hasKey("RawData")));
}
@Test
@Order(4)
void simpleSend_withVirusInAnAttachment_isRejectedLikeARawSend() {
String virus = b64(SesContentScan.signature().getBytes(StandardCharsets.US_ASCII));
String messageId = send("""
{"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["to@example.com"]},
"Content": {"Simple": {
"Subject": {"Data": "Infected"},
"Body": {"Text": {"Data": "clean body"}},
"Attachments": [{"FileName": "test.txt", "RawContent": "%s"}]}}}
""".formatted(SENDER, virus))
.then().statusCode(200).extract().path("MessageId");
given().when().get("/_aws/ses?id=" + messageId)
.then().statusCode(200)
.body("messages[0].RejectReason", equalTo("Bad content"))
.body("messages[0].Destination.ToAddresses", contains("to@example.com"))
.body("messages[0]", not(hasKey("Attachments")))
.body("messages[0]", not(hasKey("RawData")))
.body("messages[0]", not(hasKey("Subject")))
.body("messages[0]", not(hasKey("Body")));
}
@Test
@Order(5)
void simpleSend_attachmentWithoutFileName_isRejected() {
sendWithAttachments("[{\"RawContent\": \"" + b64(PDF_BYTES) + "\"}]")
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("1 validation error detected: Value at "
+ "'content.simple.attachments.1.member.fileName' failed to satisfy constraint: "
+ "Member must not be null"));
}
@Test
@Order(6)
void simpleSend_attachmentWithoutRawContent_isRejected() {
sendWithAttachments("[{\"FileName\": \"a.pdf\", \"RawContent\": \"" + b64(PDF_BYTES) + "\"},"
+ "{\"FileName\": \"b.pdf\"}]")
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("1 validation error detected: Value at "
+ "'content.simple.attachments.2.member.rawContent' failed to satisfy constraint: "
+ "Member must not be null"));
}
@Test
@Order(7)
void simpleSend_attachmentWithUnknownDisposition_isRejected() {
sendWithAttachments("[{\"FileName\": \"a.pdf\", \"RawContent\": \"" + b64(PDF_BYTES)
+ "\", \"ContentDisposition\": \"EMBEDDED\"}]")
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("1 validation error detected: Value 'EMBEDDED' at "
+ "'content.simple.attachments.1.member.contentDisposition' failed to satisfy "
+ "constraint: Member must satisfy enum value set: [ATTACHMENT, INLINE]"));
}
@Test
@Order(8)
void simpleSend_attachmentWithUnknownTransferEncoding_isRejected() {
sendWithAttachments("[{\"FileName\": \"a.pdf\", \"RawContent\": \"" + b64(PDF_BYTES)
+ "\", \"ContentTransferEncoding\": \"UUENCODE\"}]")
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", containsString("Member must satisfy enum value set: "
+ "[BASE64, QUOTED_PRINTABLE, SEVEN_BIT]"));
}
@Test
@Order(9)
void simpleSend_attachmentLengthLimits_areEnforced() {
String longName = "a".repeat(256);
sendWithAttachments("[{\"FileName\": \"" + longName + "\", \"RawContent\": \"" + b64(PDF_BYTES) + "\"}]")
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", containsString("'content.simple.attachments.1.member.fileName' failed to "
+ "satisfy constraint: Member must have length less than or equal to 255"));
sendWithAttachments("[{\"FileName\": \"a.png\", \"RawContent\": \"" + b64(PNG_BYTES)
+ "\", \"ContentId\": \"\"}]")
.then().statusCode(400)
.body("message", containsString("'content.simple.attachments.1.member.contentId' failed to "
+ "satisfy constraint: Member must have length greater than or equal to 1"));
sendWithAttachments("[{\"FileName\": \"a.png\", \"RawContent\": \"" + b64(PNG_BYTES)
+ "\", \"ContentType\": \"" + "x".repeat(79) + "\"}]")
.then().statusCode(400)
.body("message", containsString("'content.simple.attachments.1.member.contentType' failed to "
+ "satisfy constraint: Member must have length less than or equal to 78"));
sendWithAttachments("[{\"FileName\": \"a.png\", \"RawContent\": \"" + b64(PNG_BYTES)
+ "\", \"ContentDescription\": \"" + "x".repeat(1001) + "\"}]")
.then().statusCode(400)
.body("message", containsString("'content.simple.attachments.1.member.contentDescription' "
+ "failed to satisfy constraint: Member must have length less than or equal to 1000"));
}
@Test
@Order(10)
void simpleSend_attachmentWithInvalidBase64_isRejected() {
sendWithAttachments("[{\"FileName\": \"a.pdf\", \"RawContent\": \"not base64!!\"}]")
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
}
@Test
@Order(11)
void simpleSend_attachmentHeaderMembersWithLineBreaks_areRejected() {
for (String member : List.of("ContentType", "ContentDescription", "ContentId")) {
sendWithAttachments("[{\"FileName\": \"a.png\", \"RawContent\": \"" + b64(PNG_BYTES)
+ "\", \"" + member + "\": \"x\\r\\nX-Injected: yes\"}]")
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo(member + " must not contain line breaks."));
}
}
@Test
@Order(12)
void simpleSend_attachmentWithUnsupportedExtension_isRefused() {
sendWithAttachments("[{\"FileName\": \"report.pdf\", \"RawContent\": \"" + b64(PDF_BYTES) + "\"},"
+ "{\"FileName\": \"Setup.EXE\", \"RawContent\": \"" + b64(PDF_BYTES) + "\"}]")
.then().statusCode(400)
.body("__type", equalTo("MessageRejected"))
.body("message", equalTo("Message contains invalid content."));
}
@Test
@Order(13)
void rawSend_attachmentWithUnsupportedExtension_isRefused() {
String mime = "From: " + SENDER + "\r\nTo: to@example.com\r\nSubject: raw\r\n"
+ "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"b\"\r\n\r\n"
+ "--b\r\nContent-Type: text/plain\r\n\r\nbody\r\n"
+ "--b\r\nContent-Type: application/octet-stream\r\n"
+ "Content-Disposition: attachment; filename=\"macro.vbs\"\r\n"
+ "Content-Transfer-Encoding: base64\r\n\r\nAAAA\r\n--b--\r\n";
send("""
{"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["to@example.com"]},
"Content": {"Raw": {"Data": "%s"}}}
""".formatted(SENDER, b64(mime.getBytes(StandardCharsets.US_ASCII))))
.then().statusCode(400)
.body("__type", equalTo("MessageRejected"))
.body("message", equalTo("Message contains invalid content."));
}
@Test
@Order(14)
void cleanUp() {
given().header("Authorization", AUTH)
.when().delete("/v2/email/identities/" + SENDER).then().statusCode(200);
}
private static Response send(String body) {
return given().contentType("application/json").header("Authorization", AUTH)
.body(body)
.when().post("/v2/email/outbound-emails");
}
private static Response sendWithAttachments(String attachmentsJson) {
return send("""
{"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["to@example.com"]},
"Content": {"Simple": {
"Subject": {"Data": "Invalid"},
"Body": {"Text": {"Data": "body"}},
"Attachments": %s}}}
""".formatted(SENDER, attachmentsJson));
}
private static String b64(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
private static void collectLeaves(Entity entity, List<Entity> leaves) {
Body body = entity.getBody();
if (body instanceof Multipart multipart) {
for (Entity part : multipart.getBodyParts()) {
collectLeaves(part, leaves);
}
} else {
leaves.add(entity);
}
}
private static Entity leafNamed(List<Entity> leaves, String fileName) {
return leaves.stream().filter(e -> fileName.equals(e.getFilename())).findFirst()
.orElseThrow(() -> new AssertionError("no MIME part named " + fileName));
}
private static byte[] bytes(Entity entity) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
((SingleBody) entity.getBody()).writeTo(out);
return out.toByteArray();
}
private static byte[] bytesUnchecked(Entity entity) {
try {
return bytes(entity);
} catch (IOException e) {
throw new AssertionError(e);
}
}
private static String headerValue(Entity entity, String name) {
Field field = entity.getHeader().getField(name);
return field == null ? null : field.getBody().trim();
}
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.ses.model.MessageAttachment;
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
import io.vertx.core.Vertx;
import io.vertx.ext.mail.MailClient;
@@ -156,6 +157,34 @@ class SmtpRelayServerTest {
assertTrue(data.contains("plain body"), data);
}
@Test
void structuredRelay_deliversSimpleAttachmentsOverSmtp() throws Exception {
server.reset();
byte[] pdf = "PDF-PAYLOAD".getBytes(StandardCharsets.UTF_8);
byte[] png = "PNG-PAYLOAD".getBytes(StandardCharsets.UTF_8);
relayAgainstServer().relay(SmtpRelay.RelayMessage.builder("sender@example.com")
.to(List.of("to@example.com"))
.subject("With attachments")
.bodyText("plain body")
.bodyHtml("<img src=\"cid:logo\">")
.messageId("msg-9")
.attachments(List.of(
new MessageAttachment("report.pdf", pdf, "application/pdf",
MessageAttachment.Disposition.ATTACHMENT, null, null, null),
new MessageAttachment("logo.png", png, "image/png",
MessageAttachment.Disposition.INLINE, null, "logo", null)))
.build());
assertTrue(server.awaitDelivery(), "the stub server should have accepted a message");
String data = server.data();
assertTrue(data.contains("report.pdf"), data);
assertTrue(data.contains(Base64.getEncoder().encodeToString(pdf)), data);
assertTrue(data.contains("Content-ID: <logo>"), data);
assertTrue(data.contains(Base64.getEncoder().encodeToString(png)), data);
assertTrue(data.contains("multipart/related"), data);
}
@Test
void relay_authenticatesWithTheConfiguredCredentials() throws Exception {
server.reset();
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.services.ses.model.MessageAttachment;
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
import io.github.hectorvent.floci.services.ses.model.MessageTag;
import io.vertx.core.Future;
@@ -13,6 +14,7 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@@ -797,4 +799,77 @@ class SmtpRelayTest {
verify(mailClient).sendMail(captor.capture());
return captor.getValue();
}
private static MessageAttachment attachment(String name, String type,
MessageAttachment.Disposition disposition, String contentId) {
return new MessageAttachment(name, name.getBytes(StandardCharsets.UTF_8), type, disposition,
null, contentId, null);
}
@Test
void relay_simpleAttachments_inlineWithContentIdIsRelatedAndTheRestAreAttachments() {
SmtpRelay relay = enabledRelay();
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
.to(List.of("to@example.com"))
.subject("Subject")
.bodyHtml("<img src=\"cid:logo\">")
.attachments(List.of(
attachment("report.pdf", "application/pdf", MessageAttachment.Disposition.ATTACHMENT, null),
attachment("logo.png", "image/png", MessageAttachment.Disposition.INLINE, "logo"),
attachment("notes.txt", null, null, null)))
.build());
MailMessage sent = captureSent();
assertEquals(1, sent.getInlineAttachment().size());
MailAttachment logo = sent.getInlineAttachment().get(0);
assertEquals("<logo>", logo.getContentId());
assertEquals("inline", logo.getDisposition());
assertEquals("image/png", logo.getContentType());
assertEquals(2, sent.getAttachment().size());
assertEquals("attachment", sent.getAttachment().get(0).getDisposition());
assertEquals("report.pdf", sent.getAttachment().get(0).getName());
// No ContentType and no ContentDisposition: guessed from the name, relayed as an attachment.
assertEquals("text/plain", sent.getAttachment().get(1).getContentType());
assertEquals("attachment", sent.getAttachment().get(1).getDisposition());
}
@Test
void relay_inlineAttachmentWithoutHtmlBody_travelsAsAnInlineDispositionAttachment() {
SmtpRelay relay = enabledRelay();
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
.to(List.of("to@example.com"))
.subject("Subject")
.bodyText("text only")
.attachments(List.of(
attachment("logo.png", "image/png", MessageAttachment.Disposition.INLINE, "logo")))
.build());
MailMessage sent = captureSent();
assertNull(sent.getInlineAttachment());
assertEquals(1, sent.getAttachment().size());
assertEquals("inline", sent.getAttachment().get(0).getDisposition());
}
@Test
void encodeMime_simpleWithAttachments_isOneParsableMultipartMessage() throws Exception {
byte[] mime = SmtpRelay.encodeMime(SmtpRelay.RelayMessage.builder("from@example.com")
.to(List.of("to@example.com"))
.bcc(List.of("hidden@example.com"))
.subject("Subject")
.bodyText("text")
.bodyHtml("<img src=\"cid:logo\">")
.messageId("mid-1")
.attachments(List.of(
attachment("report.pdf", "application/pdf", MessageAttachment.Disposition.ATTACHMENT, null),
attachment("logo.png", "image/png", MessageAttachment.Disposition.INLINE, "logo")))
.build());
String text = new String(mime, StandardCharsets.UTF_8);
assertTrue(text.contains("Message-ID: <mid-1@email.amazonses.com>"), text);
assertEquals(text.indexOf("Message-ID:"), text.lastIndexOf("Message-ID:"), text);
assertFalse(text.contains("hidden@example.com"), text);
assertNotNull(SmtpRelay.parseMime(mime));
}
}