fix(ses): publish a Bounce for suppressionlist@simulator and split events by cause (#4073)

* fix(ses): publish a Bounce for suppressionlist@simulator and split events by cause

suppressionlist@simulator.amazonses.com published a Reject event. Real SES
publishes a hard Bounce for it: bounceType Permanent, bounceSubType General,
and a diagnostic that names the suppression. Reject is the outcome of the
content scan, which the simulator has no address for. Verified against SES
in us-east-1 on 2026-09-21 through an SNS event destination.

The same probe confirmed that a recipient on the account-level suppression
list bounces with bounceSubType OnAccountSuppressionList, or is complained
about with complaintSubType OnAccountSuppressionList, and that SES publishes
one event per cause: a message reaching both bounce@simulator and a
suppressed address produces two Bounce events, each listing only its own
recipients. Floci merged them into one General bounce.

One classifier, SesRecipientEvents, now decides the events a send produces
per recipient, and the publisher and identity notifications consume its
output, so the simulator and suppression semantics have a single home.
complaint@simulator now publishes Delivery before Complaint, as the
simulator documents, a list-management opt-out bounces under its own cause,
every bounce and complaint block carries its own feedbackId, and complaints
carry arrivalDate.

Reject stays reachable the way AWS documents it: a Simple send carrying the
EICAR test file in its subject, a header or a text body is accepted and then
rejected with reason "Bad content" and not relayed. The signature is
assembled from fragments at runtime and never appears in source. Scanning
raw MIME and keeping the signature out of the mailbox store follow
separately.

* fix(ses): drop the content of a rejected record

A send the content scan rejected was still recorded in full, so its subject,
body and headers reached the sent-email store, the inspection endpoint and,
with persistence on, the disk. The record now keeps only its source, its
envelope and RejectReason, and the inspection endpoint shows the reason.

* fix(ses): keep the scanned content out of a rejected message's events

The Send and Reject events of a rejected message carried the subject and
the additional headers in their mail block, so with headers enabled a
subject carrying the test string reached every event destination and, with
persistence on, the disk. Both events now carry the envelope but no subject
and no headers, a small deviation from SES that keeps the string off disk
entirely; the docs say so.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-09-21 21:15:52 -04:00
1 parent ccb6b63d00
commit d272cd3ceb
17 files changed
+778 -299

No files matched your search

@@ -657,9 +657,9 @@ public class SesContactService {
/**
* Resolves the recipients suppressed by SES V2 {@code SendEmail} {@code ListManagementOptions}:
* for each envelope recipient that is opted out of the named contact list (or the given topic),
* returns a {@code BOUNCE} suppression reason so the shared send path drops the recipient from
* the relay and publishes a Bounce event, matching AWS ("SES will issue a bounce event for a
* message that is sent to an unsubscribed contact"). Returns an empty map when no
* marks the recipient with {@link SesRecipientEvents#REASON_LIST_OPT_OUT} so the shared send
* path drops it from the relay and the event classifier publishes a Bounce event, matching AWS
* ("SES will issue a bounce event for a message that is sent to an unsubscribed contact"). Returns an empty map when no
* {@code ListManagementOptions} was supplied. The display-name stripping is the facade's shared
* send helper, injected as {@code addressExtractor} so this service stays free of facade
* dependencies. Throws when the contact list does not exist, so a
@@ -696,7 +696,7 @@ public class SesContactService {
}
Contact contact = getOrAutoCreateContact(list, email, region);
if (isListManagementOptedOut(contact, list, effectiveTopic)) {
optOuts.put(address, "BOUNCE");
optOuts.put(address, SesRecipientEvents.REASON_LIST_OPT_OUT);
}
}
return optOuts;
@@ -0,0 +1,45 @@
package io.github.hectorvent.floci.services.ses;
import java.util.Arrays;
/**
* The content scan SES runs on every accepted message. Real SES scans for viruses and rejects the
* whole message with a {@code Reject} event; Floci reproduces that for the one input AWS documents
* for testing it, the EICAR test file, and nothing else.
*
* <p>The EICAR string is a signature that endpoint protection quarantines on sight, so it is never
* written out verbatim: it is assembled from fragments at class initialisation, must never be
* logged or persisted, and tests obtain it from {@link #signature()} rather than spelling it out.
*/
final class SesContentScan {
private static final String[] FRAGMENTS = {
"X5O!P%@AP[4\\PZX54(P^)7CC)7}$",
"EICAR-STANDARD-",
"ANTIVIRUS-TEST-",
"FILE!$H+H*"
};
private static final String SIGNATURE_TEXT = String.join("", FRAGMENTS);
private SesContentScan() {}
/** The assembled test string, for tests that need to send it. Never log or persist it. */
static String signature() {
return SIGNATURE_TEXT;
}
/** True when any of the given texts carries the test signature. Nulls are skipped. */
static boolean containsTestVirus(String... texts) {
return containsTestVirus(Arrays.asList(texts));
}
/** True when any of the given texts carries the test signature. Nulls are skipped. */
static boolean containsTestVirus(Iterable<String> texts) {
for (String text : texts) {
if (text != null && text.contains(SIGNATURE_TEXT)) {
return true;
}
}
return false;
}
}
@@ -9,7 +9,6 @@ import io.github.hectorvent.floci.services.ses.model.MessageTag;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
@@ -32,18 +31,16 @@ final class SesEventPayload {
private SesEventPayload() {}
static ObjectNode build(ObjectMapper mapper, String eventType, String messageId, String source,
String sourceArn, String sendingAccountId, String subject,
static ObjectNode build(ObjectMapper mapper, SesRecipientEvent event, String messageId,
String source, String sourceArn, String sendingAccountId, String subject,
List<String> toAddresses, List<String> ccAddresses,
List<String> bccAddresses, List<String> envelopeDestinations,
List<String> suppressionBounceRecipients,
List<String> suppressionComplaintRecipients,
String configurationSetName, List<MessageTag> emailTags,
List<MessageHeader> additionalHeaders, Instant timestamp) {
return buildRoot(mapper, "eventType", eventType, messageId, source, sourceArn,
return buildRoot(mapper, "eventType", event, messageId, source, sourceArn,
sendingAccountId, subject, toAddresses, ccAddresses, bccAddresses,
envelopeDestinations, suppressionBounceRecipients, suppressionComplaintRecipients,
configurationSetName, emailTags, additionalHeaders, timestamp, true, true);
envelopeDestinations, configurationSetName, emailTags, additionalHeaders, timestamp,
true, true);
}
/**
@@ -59,40 +56,33 @@ final class SesEventPayload {
* the {@code BOUNCE}, {@code COMPLAINT}, and {@code DELIVERY} event types are ever published
* through this path.
*/
static ObjectNode buildIdentityNotification(ObjectMapper mapper, String eventType,
static ObjectNode buildIdentityNotification(ObjectMapper mapper, SesRecipientEvent event,
String messageId, String source, String sourceArn,
String sendingAccountId, String subject,
List<String> toAddresses, List<String> ccAddresses,
List<String> bccAddresses, List<String> envelopeDestinations,
List<String> suppressionBounceRecipients,
List<String> suppressionComplaintRecipients,
List<MessageHeader> additionalHeaders, Instant timestamp,
boolean includeHeaders) {
return buildRoot(mapper, "notificationType", eventType, messageId, source, sourceArn,
return buildRoot(mapper, "notificationType", event, messageId, source, sourceArn,
sendingAccountId, subject, toAddresses, ccAddresses, bccAddresses,
envelopeDestinations, suppressionBounceRecipients, suppressionComplaintRecipients,
null, null, additionalHeaders, timestamp, includeHeaders, false);
envelopeDestinations, null, null, additionalHeaders, timestamp, includeHeaders, false);
}
private static ObjectNode buildRoot(ObjectMapper mapper, String typeField, String eventType,
private static ObjectNode buildRoot(ObjectMapper mapper, String typeField, SesRecipientEvent event,
String messageId, String source, String sourceArn,
String sendingAccountId, String subject,
List<String> toAddresses, List<String> ccAddresses,
List<String> bccAddresses, List<String> envelopeDestinations,
List<String> suppressionBounceRecipients,
List<String> suppressionComplaintRecipients,
String configurationSetName, List<MessageTag> emailTags,
List<MessageHeader> additionalHeaders, Instant timestamp,
boolean includeHeaders, boolean includeTags) {
ObjectNode root = mapper.createObjectNode();
root.put(typeField, eventTypeLabel(eventType));
root.put(typeField, eventTypeLabel(event.eventType()));
root.set("mail", buildMail(mapper, messageId, source, sourceArn, sendingAccountId,
subject, toAddresses, ccAddresses, bccAddresses, envelopeDestinations,
configurationSetName, emailTags, additionalHeaders, timestamp,
includeHeaders, includeTags));
root.set(blockName(eventType),
buildEventBlock(mapper, eventType, messageId, envelopeDestinations,
suppressionBounceRecipients, suppressionComplaintRecipients, timestamp));
root.set(blockName(event.eventType()), buildEventBlock(mapper, event, messageId, timestamp));
return root;
}
@@ -199,42 +189,61 @@ final class SesEventPayload {
headers.add(h);
}
private static ObjectNode buildEventBlock(ObjectMapper mapper, String eventType, String messageId,
List<String> destination,
List<String> suppressionBounceRecipients,
List<String> suppressionComplaintRecipients,
Instant timestamp) {
// Probed against real SES on 2026-09-21: an account-suppressed recipient bounces with this
// subtype and diagnostic, or is complained about with this subtype and no feedback type, while
// suppressionlist@simulator is an ordinary General bounce whose diagnostic names the suppression.
static final String ON_ACCOUNT_SUPPRESSION_LIST = "OnAccountSuppressionList";
static final String ACCOUNT_SUPPRESSION_DIAGNOSTIC = "Amazon SES did not send the message to this "
+ "address because it is on the suppression list for your account. For more information "
+ "about removing addresses from the suppression list, see the Amazon SES Developer Guide "
+ "at https://docs.aws.amazon.com/ses/latest/dg/sending-email-suppression-list.html";
private static ObjectNode buildEventBlock(ObjectMapper mapper, SesRecipientEvent event,
String messageId, Instant timestamp) {
ObjectNode body = mapper.createObjectNode();
switch (eventType) {
switch (event.eventType()) {
case "DELIVERY" -> {
body.put("timestamp", ISO_MILLIS.format(timestamp));
body.put("processingTimeMillis", 0);
ArrayNode recipients = body.putArray("recipients");
for (String d : destination) {
if (SimulatorAddresses.isSuccess(d)) {
recipients.add(d.trim());
}
for (String recipient : event.recipients()) {
recipients.add(recipient);
}
body.put("smtpResponse", "250 ok");
body.put("reportingMTA", "floci");
}
case "BOUNCE" -> {
boolean suppressed = event.cause() == SesRecipientEvent.Cause.ACCOUNT_SUPPRESSION;
body.put("bounceType", "Permanent");
body.put("bounceSubType", "General");
emitDedupedRecipientObjects(body.putArray("bouncedRecipients"),
destination, SimulatorAddresses::isBounce,
suppressionBounceRecipients);
body.put("bounceSubType", suppressed ? ON_ACCOUNT_SUPPRESSION_LIST : "General");
ArrayNode bounced = body.putArray("bouncedRecipients");
for (String recipient : event.recipients()) {
ObjectNode entry = bounced.addObject();
entry.put("emailAddress", recipient);
// The shape of a list-management opt-out bounce has not been probed, so it
// carries only the address, as it did before the per-cause split.
if (event.cause() != SesRecipientEvent.Cause.LIST_MANAGEMENT) {
entry.put("action", "failed");
entry.put("status", "5.1.1");
entry.put("diagnosticCode", bounceDiagnosticCode(recipient, suppressed));
}
}
body.put("timestamp", ISO_MILLIS.format(timestamp));
body.put("feedbackId", "feedback-" + messageId);
body.put("feedbackId", feedbackId(messageId, event));
}
case "COMPLAINT" -> {
emitDedupedRecipientObjects(body.putArray("complainedRecipients"),
destination, SimulatorAddresses::isComplaint,
suppressionComplaintRecipients);
if (event.cause() == SesRecipientEvent.Cause.ACCOUNT_SUPPRESSION) {
body.put("complaintSubType", ON_ACCOUNT_SUPPRESSION_LIST);
}
ArrayNode complained = body.putArray("complainedRecipients");
for (String recipient : event.recipients()) {
complained.addObject().put("emailAddress", recipient);
}
body.put("timestamp", ISO_MILLIS.format(timestamp));
body.put("feedbackId", "feedback-" + messageId);
body.put("arrivalDate", ISO_MILLIS.format(timestamp));
body.put("feedbackId", feedbackId(messageId, event));
}
case "REJECT" -> body.put("reason", "Bad content");
case "REJECT" -> body.put("reason", SesRecipientEvents.CONTENT_REJECT_REASON);
default -> {
// SEND and other not-yet-modelled event types: empty block.
}
@@ -242,31 +251,23 @@ final class SesEventPayload {
return body;
}
/**
* Emit `{emailAddress: ...}` objects into {@code arr} for every recipient that either
* matches {@code simulatorPredicate} in {@code envelope} or is listed in
* {@code suppressionRecipients}. Addresses are trimmed and deduplicated by trimmed
* form so the same address never appears twice when both inputs claim it.
*/
private static void emitDedupedRecipientObjects(ArrayNode arr,
List<String> envelope,
java.util.function.Predicate<String> simulatorPredicate,
List<String> suppressionRecipients) {
LinkedHashSet<String> emitted = new LinkedHashSet<>();
if (envelope != null) {
for (String d : envelope) {
if (d != null && simulatorPredicate.test(d) && emitted.add(d.trim())) {
arr.addObject().put("emailAddress", d.trim());
}
}
// SES gives every bounce and complaint notification its own id, so the events split from one
// send (a simulator bounce and a suppression bounce) never share one; the id is derived rather
// than random so the configuration-set event and the identity notification of one outcome agree.
private static String feedbackId(String messageId, SesRecipientEvent event) {
return "feedback-" + messageId + "-" + event.eventType().toLowerCase(Locale.ROOT) + "-"
+ event.cause().name().toLowerCase(Locale.ROOT);
}
private static String bounceDiagnosticCode(String recipient, boolean suppressed) {
if (suppressed) {
return ACCOUNT_SUPPRESSION_DIAGNOSTIC;
}
if (suppressionRecipients != null) {
for (String d : suppressionRecipients) {
if (d != null && emitted.add(d.trim())) {
arr.addObject().put("emailAddress", d.trim());
}
}
if (SimulatorAddresses.isSuppressionList(recipient)) {
return "smtp; 550 5.1.1 As requested: user unknown (suppressed address: " + recipient + ")";
}
// The simulator documents bounce@ as an SMTP 550 5.1.1 "Unknown User" response.
return "smtp; 550 5.1.1 user unknown";
}
static String eventTypeLabel(String eventType) {
@@ -61,21 +61,19 @@ public class SesEventPublisher {
this.objectMapper = objectMapper;
}
public void publish(ConfigurationSet configurationSet, String eventType, String messageId,
public void publish(ConfigurationSet configurationSet, SesRecipientEvent event, String messageId,
String source, String sourceArn, String sendingAccountId,
String subject, List<String> toAddresses, List<String> ccAddresses,
List<String> bccAddresses, List<String> envelopeDestinations,
List<String> suppressionBounceRecipients,
List<String> suppressionComplaintRecipients,
List<MessageTag> emailTags, List<MessageHeader> additionalHeaders,
Instant timestamp, String defaultRegion) {
if (configurationSet == null || configurationSet.getEventDestinations().isEmpty()) {
return;
}
ObjectNode payload = SesEventPayload.build(objectMapper, eventType, messageId, source,
String eventType = event.eventType();
ObjectNode payload = SesEventPayload.build(objectMapper, event, messageId, source,
sourceArn, sendingAccountId, subject,
toAddresses, ccAddresses, bccAddresses, envelopeDestinations,
suppressionBounceRecipients, suppressionComplaintRecipients,
configurationSet.getName(), emailTags, additionalHeaders, timestamp);
String payloadJson = payload.toString();
for (EventDestination ed : configurationSet.getEventDestinations()) {
@@ -105,20 +103,18 @@ public class SesEventPublisher {
* {@code mail.tags}, and includes the original headers only when {@code includeHeaders} is set
* (i.e. the identity has headers-in-notifications enabled for the type).
*/
public void publishIdentityNotification(String topicArn, boolean includeHeaders, String eventType,
String messageId, String source, String sourceArn, String sendingAccountId,
String subject, List<String> toAddresses, List<String> ccAddresses,
List<String> bccAddresses, List<String> envelopeDestinations,
List<String> suppressionBounceRecipients,
List<String> suppressionComplaintRecipients,
List<MessageHeader> additionalHeaders, Instant timestamp, String defaultRegion) {
public void publishIdentityNotification(String topicArn, boolean includeHeaders,
SesRecipientEvent event, String messageId, String source, String sourceArn,
String sendingAccountId, String subject, List<String> toAddresses,
List<String> ccAddresses, List<String> bccAddresses,
List<String> envelopeDestinations, List<MessageHeader> additionalHeaders,
Instant timestamp, String defaultRegion) {
if (topicArn == null || topicArn.isBlank()) {
return;
}
ObjectNode payload = SesEventPayload.buildIdentityNotification(objectMapper, eventType,
ObjectNode payload = SesEventPayload.buildIdentityNotification(objectMapper, event,
messageId, source, sourceArn, sendingAccountId, subject,
toAddresses, ccAddresses, bccAddresses, envelopeDestinations,
suppressionBounceRecipients, suppressionComplaintRecipients,
additionalHeaders, timestamp, includeHeaders);
publishSns(topicArn, payload.toString(), defaultRegion);
}
@@ -55,6 +55,9 @@ public class SesInspectionController {
node.putNull("Region");
}
node.put("Source", email.getSource());
if (email.getRejectReason() != null) {
node.put("RejectReason", email.getRejectReason());
}
if (email.getReturnPath() != null) {
node.put("ReturnPath", email.getReturnPath());
}
@@ -0,0 +1,26 @@
package io.github.hectorvent.floci.services.ses;
import java.util.List;
/**
* One event to publish for a send: the SES event type, why it happened, and the recipients it
* concerns. A send yields one of these per (type, cause) pair, so a message that bounces for two
* different reasons publishes two {@code BOUNCE} events, as SES does.
*/
record SesRecipientEvent(String eventType, Cause cause, List<String> recipients) {
enum Cause {
/** A mailbox-simulator address, or the plain delivery of an ordinary recipient. */
SIMULATOR,
/** The recipient was on the account-level suppression list and never left Floci. */
ACCOUNT_SUPPRESSION,
/** The recipient had opted out through list management and never left Floci. */
LIST_MANAGEMENT,
/** The whole message failed the content scan and was rejected after acceptance. */
CONTENT_REJECTED
}
static SesRecipientEvent of(String eventType, Cause cause, List<String> recipients) {
return new SesRecipientEvent(eventType, cause, List.copyOf(recipients));
}
}
@@ -0,0 +1,95 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.services.ses.SesRecipientEvent.Cause;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* The one place that decides which SES events a send produces, per recipient. Configuration-set
* event publishing and the identity notifications both consume this, and anything else that
* derives a per-recipient outcome from a send should too, so the mailbox-simulator and
* suppression semantics have a single home.
*
* <p>A recipient on the account suppression list is dropped before the relay, so its outcome is
* the suppression reason regardless of its address; a list-management opt-out is dropped the same
* way but bounces under its own cause, since it is not on the suppression list. Otherwise the
* mailbox simulator decides:
* {@code success@} is delivered, {@code bounce@} and {@code suppressionlist@} both hard-bounce
* (probed 2026-09-21: the latter is an ordinary {@code General} bounce whose diagnostic text names
* the suppression, not a {@code Reject}), and {@code complaint@} is delivered and then complained
* about. An ordinary recipient produces nothing beyond {@code SEND} here; whether it counts as
* delivered is the caller's question. A rejected message publishes only {@code SEND} and
* {@code REJECT}, since SES accepts it and then refuses the whole message.
*/
final class SesRecipientEvents {
static final String REASON_BOUNCE = "BOUNCE";
static final String REASON_COMPLAINT = "COMPLAINT";
static final String REASON_LIST_OPT_OUT = "LIST_MANAGEMENT";
// The reason SES reports on a Reject event; also the marker stored on the rejected record.
static final String CONTENT_REJECT_REASON = "Bad content";
private SesRecipientEvents() {}
static List<SesRecipientEvent> classify(List<String> envelope, Map<String, String> suppressedReasons,
boolean contentRejected) {
List<SesRecipientEvent> events = new ArrayList<>();
events.add(SesRecipientEvent.of("SEND", Cause.SIMULATOR, List.of()));
if (contentRejected) {
events.add(SesRecipientEvent.of("REJECT", Cause.CONTENT_REJECTED, List.of()));
return events;
}
// Insertion order fixes the publish order: simulator outcomes, then suppression, then opt-outs.
Map<String, List<String>> groups = new LinkedHashMap<>();
for (String key : List.of(key("DELIVERY", Cause.SIMULATOR), key("BOUNCE", Cause.SIMULATOR),
key("COMPLAINT", Cause.SIMULATOR), key("BOUNCE", Cause.ACCOUNT_SUPPRESSION),
key("COMPLAINT", Cause.ACCOUNT_SUPPRESSION), key("BOUNCE", Cause.LIST_MANAGEMENT))) {
groups.put(key, new ArrayList<>());
}
if (envelope != null) {
for (String recipient : envelope) {
if (recipient == null || recipient.isBlank()) {
continue;
}
String reason = suppressedReasons == null ? null : suppressedReasons.get(recipient);
if (REASON_BOUNCE.equals(reason)) {
add(groups, "BOUNCE", Cause.ACCOUNT_SUPPRESSION, recipient);
} else if (REASON_COMPLAINT.equals(reason)) {
add(groups, "COMPLAINT", Cause.ACCOUNT_SUPPRESSION, recipient);
} else if (REASON_LIST_OPT_OUT.equals(reason)) {
add(groups, "BOUNCE", Cause.LIST_MANAGEMENT, recipient);
} else if (SimulatorAddresses.isSuccess(recipient)) {
add(groups, "DELIVERY", Cause.SIMULATOR, recipient);
} else if (SimulatorAddresses.isBounce(recipient) || SimulatorAddresses.isSuppressionList(recipient)) {
add(groups, "BOUNCE", Cause.SIMULATOR, recipient);
} else if (SimulatorAddresses.isComplaint(recipient)) {
add(groups, "DELIVERY", Cause.SIMULATOR, recipient);
add(groups, "COMPLAINT", Cause.SIMULATOR, recipient);
}
}
}
for (Map.Entry<String, List<String>> group : groups.entrySet()) {
if (group.getValue().isEmpty()) {
continue;
}
String[] parts = group.getKey().split("/");
events.add(SesRecipientEvent.of(parts[0], Cause.valueOf(parts[1]), group.getValue()));
}
return events;
}
private static String key(String eventType, Cause cause) {
return eventType + "/" + cause;
}
private static void add(Map<String, List<String>> groups, String eventType, Cause cause, String recipient) {
List<String> recipients = groups.get(key(eventType, cause));
String trimmed = recipient.trim();
if (!recipients.contains(trimmed)) {
recipients.add(trimmed);
}
}
}
@@ -235,7 +235,7 @@ public class SesService {
Map<String, String> suppressedReasons = new LinkedHashMap<>(
collectSuppressedReasons(envelope, effectiveConfigSet, region));
// putIfAbsent so a suppression-list reason already set for an address (e.g. COMPLAINT) wins
// over the list-management BOUNCE and keeps its synthetic event type.
// over the list-management opt-out and keeps its synthetic event type.
contactService.collectListManagementOptOuts(envelope, listManagement, region,
SesService::extractEmailAddress).forEach(suppressedReasons::putIfAbsent);
@@ -259,18 +259,25 @@ public class SesService {
String messageId = UUID.randomUUID().toString();
String effectiveReturnPath = firstNonBlank(returnPath, source);
// SES accepts the message and then rejects it as a whole when the content scan trips, so
// the send still succeeds and a REJECT event is published in place of any delivery.
boolean rejected = SesContentScan.containsTestVirus(subject, bodyText, bodyHtml)
|| SesContentScan.containsTestVirus(headerText(additionalHeaders));
SentEmail email = new SentEmail(messageId, region, source, toAddresses, ccAddresses,
bccAddresses, replyToAddresses, subject, bodyText, bodyHtml);
email.setReturnPath(effectiveReturnPath);
if (additionalHeaders != null && !additionalHeaders.isEmpty()) {
email.setHeaders(additionalHeaders);
}
if (rejected) {
email.discardContent(SesRecipientEvents.CONTENT_REJECT_REASON);
}
sentEmailService.record(region, messageId, email);
List<String> relayedTo = filterUnsuppressed(toAddresses, suppressedReasons);
List<String> relayedCc = filterUnsuppressed(ccAddresses, suppressedReasons);
List<String> relayedBcc = filterUnsuppressed(bccAddresses, suppressedReasons);
if (sizeOf(relayedTo) + sizeOf(relayedCc) + sizeOf(relayedBcc) > 0) {
if (!rejected && sizeOf(relayedTo) + sizeOf(relayedCc) + sizeOf(relayedBcc) > 0) {
smtpRelay.relay(SmtpRelay.RelayMessage.builder(source)
.returnPath(effectiveReturnPath)
.to(relayedTo)
@@ -284,15 +291,17 @@ public class SesService {
.messageId(messageId)
.build());
} else {
LOG.infov("SES email accepted but not relayed (all recipients suppressed): messageId={0}",
messageId);
LOG.infov("SES email accepted but not relayed ({0}): messageId={1}",
rejected ? "content rejected" : "all recipients suppressed", messageId);
}
LOG.infov("SES email sent: from={0}, to={1}, subject={2}, messageId={3}",
source, toAddresses, subject, messageId);
if (!rejected) {
LOG.infov("SES email sent: from={0}, to={1}, subject={2}, messageId={3}",
source, toAddresses, subject, messageId);
}
publishSendEvents(effectiveConfigSet, messageId, source, subject,
toAddresses, ccAddresses, bccAddresses, envelope,
suppressedReasons, emailTags, additionalHeaders, region);
suppressedReasons, rejected, emailTags, additionalHeaders, region);
return messageId;
}
@@ -349,7 +358,7 @@ public class SesService {
Map<String, String> suppressedReasons = new LinkedHashMap<>(
collectSuppressedReasons(effectiveDestinations, effectiveConfigSet, region));
// putIfAbsent so a suppression-list reason already set for an address (e.g. COMPLAINT) wins
// over the list-management BOUNCE and keeps its synthetic event type.
// over the list-management opt-out and keeps its synthetic event type.
contactService.collectListManagementOptOuts(effectiveDestinations, listManagement, region,
SesService::extractEmailAddress)
.forEach(suppressedReasons::putIfAbsent);
@@ -375,7 +384,7 @@ public class SesService {
publishSendEvents(effectiveConfigSet, messageId, effectiveSource,
headers.subject(), headers.to(), headers.cc(), headers.bcc(),
effectiveDestinations,
suppressedReasons, effectiveTags, List.of(), region);
suppressedReasons, false, effectiveTags, List.of(), region);
return messageId;
}
@@ -397,7 +406,7 @@ public class SesService {
String subject, List<String> toAddresses,
List<String> ccAddresses, List<String> bccAddresses,
List<String> envelopeDestinations,
Map<String, String> suppressedReasons,
Map<String, String> suppressedReasons, boolean contentRejected,
List<MessageTag> emailTags,
List<MessageHeader> additionalHeaders, String region) {
if (eventPublisher == null || messageId == null) {
@@ -430,30 +439,26 @@ public class SesService {
: AwsArnUtils.Arn.of("ses", region, sendingAccountId,
"identity/" + extractEmailAddress(source)).toString();
List<String> suppressionBounceRecipients = new ArrayList<>();
List<String> suppressionComplaintRecipients = new ArrayList<>();
for (Map.Entry<String, String> e : suppressedReasons.entrySet()) {
if ("BOUNCE".equals(e.getValue())) {
suppressionBounceRecipients.add(e.getKey());
} else if ("COMPLAINT".equals(e.getValue())) {
suppressionComplaintRecipients.add(e.getKey());
}
}
for (String eventType : determineSendEventTypes(envelope,
suppressionBounceRecipients, suppressionComplaintRecipients)) {
// One event per (type, cause): a message that bounces both at the simulator and on the
// suppression list publishes two BOUNCE events, each naming only its own recipients.
// A rejected message publishes none of the scanned content: its Send and Reject events
// carry the envelope but no subject and no headers, where SES would include them, so the
// string reaches no event destination either.
String publishedSubject = contentRejected ? null : subject;
List<MessageHeader> publishedHeaders = contentRejected ? List.of() : additionalHeaders;
for (SesRecipientEvent event : SesRecipientEvents.classify(envelope, suppressedReasons,
contentRejected)) {
if (configSetActive) {
eventPublisher.publish(cs, eventType, messageId, source, sourceArn, sendingAccountId,
subject, toAddresses, ccAddresses, bccAddresses, envelope,
suppressionBounceRecipients, suppressionComplaintRecipients,
emailTags, additionalHeaders, timestamp, region);
eventPublisher.publish(cs, event, messageId, source, sourceArn, sendingAccountId,
publishedSubject, toAddresses, ccAddresses, bccAddresses, envelope,
emailTags, publishedHeaders, timestamp, region);
}
IdentityNotificationTarget target = identityTargets.get(eventType);
IdentityNotificationTarget target = identityTargets.get(event.eventType());
if (target != null) {
eventPublisher.publishIdentityNotification(target.topicArn(), target.includeHeaders(),
eventType, messageId, source, sourceArn, sendingAccountId, subject,
toAddresses, ccAddresses, bccAddresses, envelope, suppressionBounceRecipients,
suppressionComplaintRecipients, additionalHeaders, timestamp, region);
event, messageId, source, sourceArn, sendingAccountId, publishedSubject,
toAddresses, ccAddresses, bccAddresses, envelope, publishedHeaders,
timestamp, region);
}
}
}
@@ -464,7 +469,7 @@ public class SesService {
* domain identity's topic, per notification type; the headers-in-notifications flag is read from
* whichever identity supplied the topic. Returns a map keyed by the {@code SEND}-style event name
* ({@code BOUNCE}/{@code COMPLAINT}/{@code DELIVERY}) so it can be looked up directly against
* {@link #determineSendEventTypes}.
* the event types {@link SesRecipientEvents#classify} produces.
*/
private Map<String, IdentityNotificationTarget> resolveIdentityNotificationTargets(String source,
String region) {
@@ -519,34 +524,6 @@ public class SesService {
return source.trim();
}
private static List<String> determineSendEventTypes(List<String> destinations,
List<String> suppressionBounceRecipients,
List<String> suppressionComplaintRecipients) {
List<String> events = new ArrayList<>();
events.add("SEND");
for (String d : destinations) {
if (SimulatorAddresses.isSuccess(d) && !events.contains("DELIVERY")) {
events.add("DELIVERY");
}
if (SimulatorAddresses.isBounce(d) && !events.contains("BOUNCE")) {
events.add("BOUNCE");
}
if (SimulatorAddresses.isComplaint(d) && !events.contains("COMPLAINT")) {
events.add("COMPLAINT");
}
if (SimulatorAddresses.isSuppressionList(d) && !events.contains("REJECT")) {
events.add("REJECT");
}
}
if (!suppressionBounceRecipients.isEmpty() && !events.contains("BOUNCE")) {
events.add("BOUNCE");
}
if (!suppressionComplaintRecipients.isEmpty() && !events.contains("COMPLAINT")) {
events.add("COMPLAINT");
}
return events;
}
public void setEmailIdentityConfigurationSet(String identityValue, String configurationSetName,
String region) {
Identity identity = identityService.find(identityValue, region)
@@ -1494,6 +1471,18 @@ public class SesService {
return results;
}
private static List<String> headerText(List<MessageHeader> headers) {
if (headers == null) {
return List.of();
}
List<String> texts = new ArrayList<>(headers.size() * 2);
for (MessageHeader header : headers) {
texts.add(header.name());
texts.add(header.value());
}
return texts;
}
private static int sizeOf(List<?> list) {
return list == null ? 0 : list.size();
}
@@ -55,6 +55,14 @@ public class SentEmail {
@JsonProperty("SentAt")
private Instant sentAt;
/**
* Set when the content scan rejected the message after acceptance. A rejected record keeps only
* its sender, its envelope and this reason, since the content is by definition something no
* store should hold.
*/
@JsonProperty("RejectReason")
private String rejectReason;
public SentEmail() {}
/** Constructor for Simple / Template content. */
@@ -129,4 +137,21 @@ public class SentEmail {
public Instant getSentAt() { return sentAt; }
public void setSentAt(Instant sentAt) { this.sentAt = sentAt; }
public String getRejectReason() { return rejectReason; }
public void setRejectReason(String rejectReason) { this.rejectReason = rejectReason; }
/**
* Drops everything but the sender, the envelope and the reason; used when the content scan
* rejects the message.
*/
public void discardContent(String reason) {
this.rejectReason = reason;
this.replyToAddresses = null;
this.subject = null;
this.headers = null;
this.bodyText = null;
this.bodyHtml = null;
this.rawData = null;
}
}