refactor(ses): model SES sends as an envelope plus content, like the v2 SDK (#4529)

* refactor(ses): model SES sends as an envelope plus content, like the v2 SDK

The five SES send methods took up to 15 positional parameters, and every
new send field cascaded through all of them and their callers. Sends now
follow the v2 SDK shape: a SendEmailRequest envelope carrying a sealed
EmailContent (Simple, Template, InlineTemplate or Raw), and a
SendBulkEmailRequest for bulk. SesService exposes sendEmail, which
switches on the content, and sendBulkEmail.

The controllers keep their validation, error codes and tenant gates;
each maps its wire input onto the envelope and picks the content
variant. The request always carries the content being sent: rendering
and header sanitizing rebuild it rather than holding a second copy.

No wire behaviour changes.

* refactor(ses): share the recipient join between the request and MIME headers
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-09-28 21:40:58 -04:00
1 parent 11b762d08b
commit 673c8838cf
15 files changed
+866 -316

No files matched your search

@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.cognito.verification;
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.ses.SesService;
import io.github.hectorvent.floci.services.ses.model.EmailContent;
import io.github.hectorvent.floci.services.ses.model.SendEmailRequest;
import io.github.hectorvent.floci.services.sns.SnsService;
import java.util.List;
@@ -67,21 +69,12 @@ public final class CognitoMessageDispatcher {
String rawBody = stringOrNull(customMessageResponse, "emailMessage");
if (rawBody == null) rawBody = stringOr(template.get(emailTemplateKey()), DEFAULT_EMAIL_BODY);
String body = renderTemplate(rawBody, code);
ses.sendEmail(
DEFAULT_FROM,
List.of(email),
List.of(), List.of(), List.of(),
null, // returnPath
subject,
body,
null, // bodyHtml
null, // configurationSetName
List.of(), // emailTags
List.of(), // additionalHeaders
null, // listManagement
null, // tenantName
DEFAULT_REGION
);
ses.sendEmail(SendEmailRequest.builder()
.source(DEFAULT_FROM)
.toAddresses(List.of(email))
.region(DEFAULT_REGION)
.content(new EmailContent.Simple(subject, body, null, List.of()))
.build());
} else if ("SMS".equalsIgnoreCase(medium) && phone != null) {
String rawBody = stringOrNull(customMessageResponse, "smsMessage");
if (rawBody == null) rawBody = stringOr(resolveSmsTemplate(pool, template, purpose), DEFAULT_SMS_BODY);
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.ses.model.CloudWatchDimensionConfigur
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.DeliveryOptions;
import io.github.hectorvent.floci.services.ses.model.EmailContent;
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
import io.github.hectorvent.floci.services.ses.model.EventDestination;
import io.github.hectorvent.floci.services.ses.model.Identity;
@@ -21,6 +22,8 @@ import io.github.hectorvent.floci.services.ses.model.ReceiptAction;
import io.github.hectorvent.floci.services.ses.model.ReceiptFilter;
import io.github.hectorvent.floci.services.ses.model.ReceiptRule;
import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet;
import io.github.hectorvent.floci.services.ses.model.SendBulkEmailRequest;
import io.github.hectorvent.floci.services.ses.model.SendEmailRequest;
import io.github.hectorvent.floci.services.ses.model.SnsDestination;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -253,9 +256,18 @@ public class SesQueryHandler {
List<MessageTag> emailTags = extractMessageTags(params, "Tags");
// ListManagementOptions is a v2-only SendEmail field; the v1 Query API has no equivalent.
String messageId = sesService.sendEmail(source, toAddresses, ccAddresses, bccAddresses,
replyToAddresses, returnPath, subject, bodyText, bodyHtml, configurationSetName,
emailTags, List.of(), null, null, region);
String messageId = sesService.sendEmail(SendEmailRequest.builder()
.source(source)
.toAddresses(toAddresses)
.ccAddresses(ccAddresses)
.bccAddresses(bccAddresses)
.replyToAddresses(replyToAddresses)
.returnPath(returnPath)
.configurationSetName(configurationSetName)
.emailTags(emailTags)
.region(region)
.content(new EmailContent.Simple(subject, bodyText, bodyHtml, List.of()))
.build());
String result = new XmlBuilder().elem("MessageId", messageId).build();
return Response.ok(AwsQueryResponse.envelope("SendEmail", AwsNamespaces.SES, result)).build();
@@ -272,8 +284,14 @@ public class SesQueryHandler {
String configurationSetName = getParam(params, "ConfigurationSetName");
List<MessageTag> emailTags = extractMessageTags(params, "Tags");
String messageId = sesService.sendRawEmail(source, destinations, rawMessage,
null, configurationSetName, emailTags, null, null, region);
String messageId = sesService.sendEmail(SendEmailRequest.builder()
.source(source)
.toAddresses(destinations)
.configurationSetName(configurationSetName)
.emailTags(emailTags)
.region(region)
.content(new EmailContent.Raw(rawMessage))
.build());
String result = new XmlBuilder().elem("MessageId", messageId).build();
return Response.ok(AwsQueryResponse.envelope("SendRawEmail", AwsNamespaces.SES, result)).build();
@@ -609,9 +627,18 @@ public class SesQueryHandler {
String configurationSetName = getParam(params, "ConfigurationSetName");
String returnPath = getParam(params, "ReturnPath");
List<MessageTag> emailTags = extractMessageTags(params, "Tags");
String messageId = sesService.sendTemplatedEmail(source, toAddresses, ccAddresses,
bccAddresses, replyToAddresses, returnPath, resolvedName, templateData,
configurationSetName, emailTags, List.of(), null, null, region);
String messageId = sesService.sendEmail(SendEmailRequest.builder()
.source(source)
.toAddresses(toAddresses)
.ccAddresses(ccAddresses)
.bccAddresses(bccAddresses)
.replyToAddresses(replyToAddresses)
.returnPath(returnPath)
.configurationSetName(configurationSetName)
.emailTags(emailTags)
.region(region)
.content(new EmailContent.Template(resolvedName, templateData, List.of()))
.build());
String result = new XmlBuilder().elem("MessageId", messageId).build();
return Response.ok(AwsQueryResponse.envelope("SendTemplatedEmail", AwsNamespaces.SES, result)).build();
@@ -755,10 +782,17 @@ public class SesQueryHandler {
String configurationSetName = getParam(params, "ConfigurationSetName");
String returnPath = getParam(params, "ReturnPath");
List<MessageTag> defaultEmailTags = extractMessageTags(params, "DefaultTags");
List<BulkEmailEntryResult> results = sesService.sendBulkTemplatedEmail(source, replyToAddresses,
returnPath, template.getSubject(), template.getTextPart(), template.getHtmlPart(),
defaultTemplateData, entries, configurationSetName,
defaultEmailTags, List.of(), null, region);
List<BulkEmailEntryResult> results = sesService.sendBulkEmail(SendBulkEmailRequest.builder()
.source(source)
.replyToAddresses(replyToAddresses)
.returnPath(returnPath)
.configurationSetName(configurationSetName)
.defaultEmailTags(defaultEmailTags)
.region(region)
.defaultContent(new EmailContent.InlineTemplate(template.getSubject(), template.getTextPart(),
template.getHtmlPart(), defaultTemplateData, List.of()))
.entries(entries)
.build());
XmlBuilder xml = new XmlBuilder().start("Status");
for (BulkEmailEntryResult result : results) {
@@ -9,10 +9,13 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.ses.model.BulkEmailEntry;
import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult;
import io.github.hectorvent.floci.services.ses.model.EmailContent;
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
import io.github.hectorvent.floci.services.ses.model.ListManagementOptions;
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
import io.github.hectorvent.floci.services.ses.model.MessageTag;
import io.github.hectorvent.floci.services.ses.model.SendBulkEmailRequest;
import io.github.hectorvent.floci.services.ses.model.SendEmailRequest;
import io.github.hectorvent.floci.services.ses.model.Tag;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
@@ -101,13 +104,24 @@ public class SesSendController {
List<String> replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses"));
String feedbackForwardingAddress =
request.path("FeedbackForwardingEmailAddress").asText(null);
List<String> allDestinations = mergeLists(toAddresses, ccAddresses, bccAddresses);
String configurationSetName = request.path("ConfigurationSetName").asText(null);
String tenantName = stringMemberOrAbsent(request, "TenantName");
List<MessageTag> emailTags = parseEmailTagsArray(request.path("EmailTags"), "EmailTags");
ListManagementOptions listManagement =
parseListManagementOptions(request.path("ListManagementOptions"));
SendEmailRequest.Builder sendRequest = SendEmailRequest.builder()
.source(fromEmailAddress)
.toAddresses(toAddresses)
.ccAddresses(ccAddresses)
.bccAddresses(bccAddresses)
.replyToAddresses(replyToAddresses)
.returnPath(feedbackForwardingAddress)
.configurationSetName(configurationSetName)
.emailTags(emailTags)
.listManagement(listManagement)
.tenantName(tenantName)
.region(region);
JsonNode content = request.path("Content");
String messageId;
@@ -117,15 +131,13 @@ public class SesSendController {
throw new AwsException("BadRequestException",
"Content.Raw.Data is required.", 400);
}
if (allDestinations.isEmpty()) {
if (toAddresses.isEmpty() && ccAddresses.isEmpty() && bccAddresses.isEmpty()) {
throw new AwsException("BadRequestException",
"At least one destination address is required.", 400);
}
sesService.checkTenantRawSendAccess(tenantName, fromEmailAddress, rawData,
configurationSetName, regionResolver.getAccountId(), region);
messageId = sesService.sendRawEmail(fromEmailAddress, allDestinations, rawData,
feedbackForwardingAddress, configurationSetName, emailTags, listManagement,
tenantName, region);
messageId = sesService.sendEmail(sendRequest.content(new EmailContent.Raw(rawData)).build());
} else if (content.has("Simple")) {
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
// AWS returns BadRequestException with a null message body here.
@@ -139,11 +151,9 @@ public class SesSendController {
parseHeadersArray(simple.path("Headers"), "content.simple.headers");
sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName,
null, regionResolver.getAccountId(), region);
messageId = sesService.sendEmail(fromEmailAddress, toAddresses, ccAddresses,
bccAddresses, replyToAddresses, feedbackForwardingAddress,
subject, bodyText, bodyHtml,
configurationSetName, emailTags, additionalHeaders, listManagement,
tenantName, region);
messageId = sesService.sendEmail(sendRequest
.content(new EmailContent.Simple(subject, bodyText, bodyHtml, additionalHeaders))
.build());
} else if (content.has("Template")) {
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
throw new AwsException("BadRequestException", "Source cannot be empty", 400);
@@ -173,10 +183,9 @@ public class SesSendController {
: SesTemplateService.templateNameFromArn(templateArn);
sesService.checkTenantSendAccess(tenantName, fromEmailAddress,
configurationSetName, resolvedName, regionResolver.getAccountId(), region);
messageId = sesService.sendTemplatedEmail(fromEmailAddress, toAddresses, ccAddresses,
bccAddresses, replyToAddresses, feedbackForwardingAddress,
resolvedName, templateData,
configurationSetName, emailTags, additionalHeaders, listManagement, tenantName, region);
messageId = sesService.sendEmail(sendRequest
.content(new EmailContent.Template(resolvedName, templateData, additionalHeaders))
.build());
} else {
JsonNode inline = template.path("TemplateContent");
String subject = inline.path("Subject").asText(null);
@@ -188,10 +197,10 @@ public class SesSendController {
SesService.requireInlineTemplateContent(subject, text, html);
sesService.checkTenantSendAccess(tenantName, fromEmailAddress,
configurationSetName, null, regionResolver.getAccountId(), region);
messageId = sesService.sendInlineTemplatedEmail(fromEmailAddress, toAddresses,
ccAddresses, bccAddresses, replyToAddresses, feedbackForwardingAddress,
subject, text, html, templateData,
configurationSetName, emailTags, additionalHeaders, listManagement, tenantName, region);
messageId = sesService.sendEmail(sendRequest
.content(new EmailContent.InlineTemplate(subject, text, html, templateData,
additionalHeaders))
.build());
}
} else {
throw new AwsException("BadRequestException",
@@ -316,10 +325,18 @@ public class SesSendController {
sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName,
gateTemplateName, regionResolver.getAccountId(), region);
List<BulkEmailEntryResult> results = sesService.sendBulkTemplatedEmail(fromEmailAddress,
replyToAddresses, feedbackForwardingAddress, subject, text, html,
defaultTemplateData, entries, configurationSetName,
defaultEmailTags, defaultHeaders, tenantName, region);
List<BulkEmailEntryResult> results = sesService.sendBulkEmail(SendBulkEmailRequest.builder()
.source(fromEmailAddress)
.replyToAddresses(replyToAddresses)
.returnPath(feedbackForwardingAddress)
.configurationSetName(configurationSetName)
.defaultEmailTags(defaultEmailTags)
.tenantName(tenantName)
.region(region)
.defaultContent(new EmailContent.InlineTemplate(subject, text, html, defaultTemplateData,
defaultHeaders))
.entries(entries)
.build());
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = response.putArray("BulkEmailEntryResults");
@@ -390,13 +407,6 @@ public class SesSendController {
return list;
}
private List<String> mergeLists(List<String> to, List<String> cc, List<String> bcc) {
List<String> all = new ArrayList<>(to);
all.addAll(cc);
all.addAll(bcc);
return all;
}
private JsonNode parseTemplateData(JsonNode parent, String fieldName) {
if (parent == null || parent.isMissingNode() || parent.isNull()) {
return objectMapper.createObjectNode();
@@ -11,11 +11,13 @@ import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
import io.github.hectorvent.floci.services.ses.model.Contact;
import io.github.hectorvent.floci.services.ses.model.CustomVerificationEmailTemplate;
import io.github.hectorvent.floci.services.ses.model.DeliveryOptions;
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
import io.github.hectorvent.floci.services.ses.model.EmailContent;
import io.github.hectorvent.floci.services.ses.model.Identity;
import io.github.hectorvent.floci.services.ses.model.ListManagementOptions;
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
import io.github.hectorvent.floci.services.ses.model.MessageTag;
import io.github.hectorvent.floci.services.ses.model.SendBulkEmailRequest;
import io.github.hectorvent.floci.services.ses.model.SendEmailRequest;
import io.github.hectorvent.floci.services.ses.model.Topic;
import io.github.hectorvent.floci.services.ses.model.TrackingOptions;
import io.github.hectorvent.floci.services.ses.model.SentEmail;
@@ -212,67 +214,82 @@ public class SesService {
LOG.infov("Deleted identity: {0}", identityValue);
}
public String sendEmail(String source, List<String> toAddresses, List<String> ccAddresses,
List<String> bccAddresses, List<String> replyToAddresses, String returnPath,
String subject, String bodyText, String bodyHtml,
String configurationSetName, List<MessageTag> emailTags,
List<MessageHeader> additionalHeaders, ListManagementOptions listManagement,
String tenantName, String region) {
public String sendEmail(SendEmailRequest request) {
return switch (request.content()) {
case EmailContent.Simple simple -> sendSimpleEmail(request, simple);
case EmailContent.Template template ->
sendInlineTemplatedEmail(request, templateService.inline(template, request.region()));
case EmailContent.InlineTemplate inline -> sendInlineTemplatedEmail(request, inline);
case EmailContent.Raw raw -> sendRawEmail(request, raw);
};
}
private String sendInlineTemplatedEmail(SendEmailRequest request, EmailContent.InlineTemplate template) {
requireInlineTemplateContent(template.subject(), template.textPart(), template.htmlPart());
EmailContent.Simple rendered = SesTemplateService.render(template);
return sendSimpleEmail(request.toBuilder().content(rendered).build(), rendered);
}
private String sendSimpleEmail(SendEmailRequest request, EmailContent.Simple content) {
String source = request.source();
String region = request.region();
if (source == null || source.isBlank()) {
throw new AwsException("InvalidParameterValue", "Source email is required.", 400);
}
boolean hasRecipient = (toAddresses != null && !toAddresses.isEmpty())
|| (ccAddresses != null && !ccAddresses.isEmpty())
|| (bccAddresses != null && !bccAddresses.isEmpty());
if (!hasRecipient) {
if (!request.hasRecipients()) {
throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400);
}
String effectiveConfigSet = resolveDefaultConfigurationSet(configurationSetName, source, region);
String effectiveConfigSet = resolveDefaultConfigurationSet(request.configurationSetName(), source, region);
configSetService.validateForSending(effectiveConfigSet, region);
// Resolve suppression before recording the message so a bad ListManagementOptions (e.g. an
// unknown contact list) fails the whole send without leaving an orphaned SentEmail record.
List<String> envelope = allRecipients(toAddresses, ccAddresses, bccAddresses);
List<String> envelope = request.recipients();
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 opt-out and keeps its synthetic event type.
contactService.collectListManagementOptOuts(envelope, listManagement, region,
contactService.collectListManagementOptOuts(envelope, request.listManagement(), region,
SesService::extractEmailAddress).forEach(suppressedReasons::putIfAbsent);
// A single-recipient list-managed send gets a functional unsubscribe link: the
// {{amazonSESUnsubscribeUrl}} body placeholder is replaced and the List-Unsubscribe headers
// are added, matching AWS (which only injects these for a single recipient). The link
// resolves to Floci's own /_aws/ses/unsubscribe endpoint.
if (hasListManagement(listManagement) && envelope.size() == 1) {
String url = buildUnsubscribeUrl(region, listManagement, extractEmailAddress(envelope.get(0)));
bodyText = replaceUnsubscribePlaceholder(bodyText, url);
bodyHtml = replaceUnsubscribePlaceholder(bodyHtml, url);
additionalHeaders = withUnsubscribeHeaders(additionalHeaders, url);
if (hasListManagement(request.listManagement()) && envelope.size() == 1) {
String url = buildUnsubscribeUrl(region, request.listManagement(), extractEmailAddress(envelope.get(0)));
content = new EmailContent.Simple(content.subject(),
replaceUnsubscribePlaceholder(content.bodyText(), url),
replaceUnsubscribePlaceholder(content.bodyHtml(), url),
withUnsubscribeHeaders(content.headers(), url));
request = request.toBuilder().content(content).build();
}
// Drop unsafe user-supplied headers (blank name or CR/LF in name/value) once here, so the
// stored SentEmail, the SMTP relay, and the published events all reflect the same sanitized
// set and no injection payload is retained on any surface.
if (additionalHeaders != null) {
additionalHeaders = additionalHeaders.stream().filter(MessageHeader::isSafe).toList();
if (content.hasHeaders()) {
content = content.withSafeHeaders();
request = request.toBuilder().content(content).build();
}
String messageId = UUID.randomUUID().toString();
String effectiveReturnPath = firstNonBlank(returnPath, source);
String effectiveReturnPath = firstNonBlank(request.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);
boolean rejected = SesContentScan.containsTestVirus(content.subject(), content.bodyText(),
content.bodyHtml())
|| SesContentScan.containsTestVirus(headerText(content.headers()));
SentEmail email = new SentEmail(messageId, region, source, request.toAddresses(),
request.ccAddresses(), request.bccAddresses(), request.replyToAddresses(), content.subject(),
content.bodyText(), content.bodyHtml());
email.setReturnPath(effectiveReturnPath);
email.setConfigurationSetName(firstNonBlank(effectiveConfigSet));
email.setTenantName(firstNonBlank(tenantName));
if (additionalHeaders != null && !additionalHeaders.isEmpty()) {
email.setHeaders(additionalHeaders);
email.setTenantName(firstNonBlank(request.tenantName()));
if (content.hasHeaders()) {
email.setHeaders(content.headers());
}
email.setEmailTags(emailTags);
email.setEmailTags(request.emailTags());
email.setInsights(SesMessageInsights.build(envelope,
SesRecipientEvents.classify(envelope, suppressedReasons, rejected), email.getSentAt()));
if (rejected) {
@@ -280,20 +297,20 @@ public class SesService {
}
sentEmailService.record(region, messageId, email);
List<String> relayedTo = filterUnsuppressed(toAddresses, suppressedReasons);
List<String> relayedCc = filterUnsuppressed(ccAddresses, suppressedReasons);
List<String> relayedBcc = filterUnsuppressed(bccAddresses, suppressedReasons);
List<String> relayedTo = filterUnsuppressed(request.toAddresses(), suppressedReasons);
List<String> relayedCc = filterUnsuppressed(request.ccAddresses(), suppressedReasons);
List<String> relayedBcc = filterUnsuppressed(request.bccAddresses(), suppressedReasons);
if (!rejected && sizeOf(relayedTo) + sizeOf(relayedCc) + sizeOf(relayedBcc) > 0) {
smtpRelay.relay(SmtpRelay.RelayMessage.builder(source)
.returnPath(effectiveReturnPath)
.to(relayedTo)
.cc(relayedCc)
.bcc(relayedBcc)
.replyTo(replyToAddresses)
.subject(subject)
.bodyText(bodyText)
.bodyHtml(bodyHtml)
.headers(additionalHeaders)
.replyTo(request.replyToAddresses())
.subject(content.subject())
.bodyText(content.bodyText())
.bodyHtml(content.bodyHtml())
.headers(content.headers())
.messageId(messageId)
.build());
} else {
@@ -303,18 +320,19 @@ public class SesService {
if (!rejected) {
LOG.infov("SES email sent: from={0}, to={1}, subject={2}, messageId={3}",
source, toAddresses, subject, messageId);
source, request.toAddresses(), content.subject(), messageId);
}
publishSendEvents(effectiveConfigSet, messageId, source, subject,
toAddresses, ccAddresses, bccAddresses, envelope,
suppressedReasons, rejected, emailTags, additionalHeaders, region);
publishSendEvents(effectiveConfigSet, messageId, source, content.subject(),
request.toAddresses(), request.ccAddresses(), request.bccAddresses(), envelope,
suppressedReasons, rejected, request.emailTags(), content.headers(), region);
return messageId;
}
public String sendRawEmail(String source, List<String> destinations, String rawMessage,
String returnPath, String configurationSetName, List<MessageTag> emailTags,
ListManagementOptions listManagement, String tenantName, String region) {
if (rawMessage == null || rawMessage.isBlank()) {
private String sendRawEmail(SendEmailRequest request, EmailContent.Raw raw) {
String source = request.source();
String region = request.region();
List<String> destinations = request.recipients();
if (raw.data() == null || raw.data().isBlank()) {
throw new AwsException("InvalidParameterValue", "RawMessage.Data is required.", 400);
}
boolean hasExplicitDestinations = destinations != null && !destinations.isEmpty();
@@ -322,19 +340,19 @@ public class SesService {
// The MIME headers are always parsed: X-SES-CONFIGURATION-SET can name the configuration
// set that decides whether events are published at all, so the configuration set cannot be
// resolved before the message has been read.
SmtpRelay.ParsedRawMessage parsed = SmtpRelay.parseRawMessage(rawMessage);
SmtpRelay.ParsedRawMessage parsed = SmtpRelay.parseRawMessage(raw.data());
SmtpRelay.RawMessageHeaders headers = parsed.headers();
// AWS accepts the configuration set either as a request field or as the
// X-SES-CONFIGURATION-SET header on the message itself; the request field wins.
String requestedConfigSet = firstNonBlank(configurationSetName, headers.configurationSet());
String requestedConfigSet = firstNonBlank(request.configurationSetName(), headers.configurationSet());
String effectiveConfigSet = resolveDefaultConfigurationSet(requestedConfigSet, source, region);
configSetService.validateForSending(effectiveConfigSet, region);
// Message tags work differently: AWS uses only the request field's tags when both are
// present and does not join the two sets, so the header tags apply only when no tag was
// passed as a parameter.
List<MessageTag> effectiveTags = (emailTags == null || emailTags.isEmpty())
List<MessageTag> effectiveTags = (request.emailTags() == null || request.emailTags().isEmpty())
? headers.messageTags()
: emailTags;
: request.emailTags();
String effectiveSource = sourceOmitted && !headers.from().isBlank()
? headers.from()
: source;
@@ -355,7 +373,7 @@ public class SesService {
}
List<String> effectiveDestinations = hasExplicitDestinations
? destinations
: allRecipients(headers.to(), headers.cc(), headers.bcc());
: SendEmailRequest.recipients(headers.to(), headers.cc(), headers.bcc());
if (effectiveDestinations.isEmpty()) {
throw new AwsException("InvalidParameterValue",
"At least one destination address is required.", 400);
@@ -366,7 +384,7 @@ public class SesService {
collectSuppressedReasons(effectiveDestinations, effectiveConfigSet, region));
// putIfAbsent so a suppression-list reason already set for an address (e.g. COMPLAINT) wins
// over the list-management opt-out and keeps its synthetic event type.
contactService.collectListManagementOptOuts(effectiveDestinations, listManagement, region,
contactService.collectListManagementOptOuts(effectiveDestinations, request.listManagement(), region,
SesService::extractEmailAddress)
.forEach(suppressedReasons::putIfAbsent);
@@ -383,19 +401,19 @@ public class SesService {
// own headers, and that header's value reaches here unparsed, so it is dropped; an envelope
// read off the headers is a list of parsed addresses and carries no message text.
String effectiveReturnPath = rejected
? firstNonBlank(returnPath, effectiveSource)
: firstNonBlank(headers.returnPath(), returnPath, effectiveSource);
SentEmail email = new SentEmail(messageId, region, effectiveSource, effectiveDestinations, rawMessage);
? firstNonBlank(request.returnPath(), effectiveSource)
: firstNonBlank(headers.returnPath(), request.returnPath(), effectiveSource);
SentEmail email = new SentEmail(messageId, region, effectiveSource, effectiveDestinations, raw.data());
email.setReturnPath(effectiveReturnPath);
email.setConfigurationSetName(firstNonBlank(effectiveConfigSet));
email.setTenantName(firstNonBlank(tenantName));
email.setTenantName(firstNonBlank(request.tenantName()));
// The MIME subject is already parsed for the published events; store it too so
// GetMessageInsights reports it for a raw send as it does for a simple one. The parser
// yields "" for a missing header, and an absent subject must stay absent.
email.setSubject(firstNonBlank(headers.subject()));
// A rejected message publishes only the tags that came with the request, so the stored
// record keeps the same set: tags read off its headers must not resurface through insights.
email.setEmailTags(rejected ? requestTags(emailTags) : effectiveTags);
email.setEmailTags(rejected ? requestTags(request.emailTags()) : effectiveTags);
email.setInsights(SesMessageInsights.build(effectiveDestinations,
SesRecipientEvents.classify(effectiveDestinations, suppressedReasons, rejected),
email.getSentAt()));
@@ -407,7 +425,7 @@ public class SesService {
List<String> relayedDestinations = filterUnsuppressed(effectiveDestinations, suppressedReasons);
if (!rejected && !relayedDestinations.isEmpty()) {
smtpRelay.relayRaw(new SmtpRelay.RawRelayMessage(effectiveSource, effectiveReturnPath,
relayedDestinations, rawMessage, messageId));
relayedDestinations, raw.data(), messageId));
} else {
LOG.infov("SES raw email accepted but not relayed ({0}): messageId={1}",
rejected ? "content rejected" : "all recipients suppressed", messageId);
@@ -424,24 +442,11 @@ public class SesService {
publishSendEvents(effectiveConfigSet, messageId, effectiveSource,
headers.subject(), publishedTo, publishedCc, publishedBcc,
effectiveDestinations,
suppressedReasons, rejected, rejected ? requestTags(emailTags) : effectiveTags, List.of(), region);
suppressedReasons, rejected, rejected ? requestTags(request.emailTags()) : effectiveTags,
List.of(), region);
return messageId;
}
private static List<String> allRecipients(List<String> to, List<String> cc, List<String> bcc) {
List<String> all = new ArrayList<>();
if (to != null) {
all.addAll(to);
}
if (cc != null) {
all.addAll(cc);
}
if (bcc != null) {
all.addAll(bcc);
}
return all;
}
private void publishSendEvents(String configurationSetName, String messageId, String source,
String subject, List<String> toAddresses,
List<String> ccAddresses, List<String> bccAddresses,
@@ -1429,20 +1434,6 @@ public class SesService {
return effective.contains(entry.getReason()) ? entry.getReason() : null;
}
public String sendTemplatedEmail(String source, List<String> toAddresses, List<String> ccAddresses,
List<String> bccAddresses, List<String> replyToAddresses,
String returnPath, String templateName, JsonNode templateData,
String configurationSetName, List<MessageTag> emailTags,
List<MessageHeader> additionalHeaders,
ListManagementOptions listManagement, String tenantName, String region) {
EmailTemplate template = templateService.getTemplate(templateName, region);
return sendInlineTemplatedEmail(source, toAddresses, ccAddresses, bccAddresses,
replyToAddresses, returnPath, template.getSubject(), template.getTextPart(),
template.getHtmlPart(), templateData,
configurationSetName, emailTags, additionalHeaders, listManagement,
tenantName, region);
}
/**
* Also called by the controller ahead of the tenant send gate: AWS reports an empty inline
* template before it looks the tenant up (probe-confirmed), so the check must not stay behind
@@ -1458,48 +1449,23 @@ public class SesService {
}
}
public String sendInlineTemplatedEmail(String source, List<String> toAddresses, List<String> ccAddresses,
List<String> bccAddresses, List<String> replyToAddresses,
String returnPath,
String subject, String textPart, String htmlPart,
JsonNode templateData,
String configurationSetName, List<MessageTag> emailTags,
List<MessageHeader> additionalHeaders,
ListManagementOptions listManagement, String tenantName, String region) {
requireInlineTemplateContent(subject, textPart, htmlPart);
return sendEmail(source, toAddresses, ccAddresses, bccAddresses, replyToAddresses, returnPath,
SesTemplateService.applyTemplateData(subject, templateData),
SesTemplateService.applyTemplateData(textPart, templateData),
SesTemplateService.applyTemplateData(htmlPart, templateData),
configurationSetName, emailTags, additionalHeaders, listManagement,
tenantName, region);
}
public List<BulkEmailEntryResult> sendBulkTemplatedEmail(String source,
List<String> replyToAddresses,
String returnPath,
String subject, String textPart, String htmlPart,
JsonNode defaultTemplateData,
List<BulkEmailEntry> entries,
String configurationSetName,
List<MessageTag> defaultEmailTags,
List<MessageHeader> defaultHeaders,
String tenantName, String region) {
if (source == null || source.isBlank()) {
public List<BulkEmailEntryResult> sendBulkEmail(SendBulkEmailRequest request) {
EmailContent.InlineTemplate template = request.defaultContent();
if (request.source() == null || request.source().isBlank()) {
throw new AwsException("InvalidParameterValue", "Source email is required.", 400);
}
requireInlineTemplateContent(subject, textPart, htmlPart);
if (entries == null || entries.isEmpty()) {
requireInlineTemplateContent(template.subject(), template.textPart(), template.htmlPart());
if (request.entries() == null || request.entries().isEmpty()) {
throw new AwsException("InvalidParameterValue",
"At least one destination entry is required.", 400);
}
configSetService.validateForSending(configurationSetName, region);
if (entries.size() > MAX_BULK_DESTINATIONS) {
configSetService.validateForSending(request.configurationSetName(), request.region());
if (request.entries().size() > MAX_BULK_DESTINATIONS) {
throw new AwsException("MessageRejected",
"Number of destinations (" + entries.size() + ") exceeds the maximum of "
"Number of destinations (" + request.entries().size() + ") exceeds the maximum of "
+ MAX_BULK_DESTINATIONS + ".", 400);
}
for (BulkEmailEntry entry : entries) {
for (BulkEmailEntry entry : request.entries()) {
int recipientCount = sizeOf(entry.toAddresses())
+ sizeOf(entry.ccAddresses())
+ sizeOf(entry.bccAddresses());
@@ -1510,21 +1476,30 @@ public class SesService {
}
}
List<BulkEmailEntryResult> results = new ArrayList<>(entries.size());
for (BulkEmailEntry entry : entries) {
List<BulkEmailEntryResult> results = new ArrayList<>(request.entries().size());
for (BulkEmailEntry entry : request.entries()) {
try {
JsonNode merged = mergeTemplateData(defaultTemplateData, entry.replacementTemplateData());
List<MessageTag> mergedTags = mergeEmailTags(defaultEmailTags, entry.replacementEmailTags());
List<MessageHeader> mergedHeaders = mergeHeaders(defaultHeaders, entry.replacementHeaders());
JsonNode merged = mergeTemplateData(template.templateData(), entry.replacementTemplateData());
List<MessageTag> mergedTags = mergeEmailTags(request.defaultEmailTags(), entry.replacementEmailTags());
List<MessageHeader> mergedHeaders = mergeHeaders(template.headers(), entry.replacementHeaders());
EmailContent.Simple rendered = SesTemplateService.render(new EmailContent.InlineTemplate(
template.subject(), template.textPart(), template.htmlPart(), merged, mergedHeaders));
// SendBulkEmail has no ListManagementOptions field, so list-managed suppression
// does not apply to bulk sends.
String messageId = sendEmail(source,
entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses(),
replyToAddresses, returnPath,
SesTemplateService.applyTemplateData(subject, merged),
SesTemplateService.applyTemplateData(textPart, merged),
SesTemplateService.applyTemplateData(htmlPart, merged),
configurationSetName, mergedTags, mergedHeaders, null, tenantName, region);
// does not apply to bulk sends and the entry request leaves it unset.
SendEmailRequest entryRequest = SendEmailRequest.builder()
.source(request.source())
.toAddresses(entry.toAddresses())
.ccAddresses(entry.ccAddresses())
.bccAddresses(entry.bccAddresses())
.replyToAddresses(request.replyToAddresses())
.returnPath(request.returnPath())
.configurationSetName(request.configurationSetName())
.emailTags(mergedTags)
.tenantName(request.tenantName())
.region(request.region())
.content(rendered)
.build();
String messageId = sendSimpleEmail(entryRequest, rendered);
results.add(BulkEmailEntryResult.success(messageId));
} catch (AwsException e) {
results.add(BulkEmailEntryResult.failure(
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ses.model.EmailContent;
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
import io.github.hectorvent.floci.services.ses.model.Tag;
import jakarta.enterprise.context.ApplicationScoped;
@@ -90,6 +91,12 @@ public class SesTemplateService {
"Template " + templateName + " does not exist.", 400));
}
EmailContent.InlineTemplate inline(EmailContent.Template template, String region) {
EmailTemplate stored = getTemplate(template.templateName(), region);
return new EmailContent.InlineTemplate(stored.getSubject(), stored.getTextPart(),
stored.getHtmlPart(), template.templateData(), template.headers());
}
public EmailTemplate updateTemplate(EmailTemplate template, String region) {
validateTemplate(template);
String key = templateKey(region, template.getTemplateName());
@@ -249,6 +256,14 @@ public class SesTemplateService {
return node;
}
static EmailContent.Simple render(EmailContent.InlineTemplate template) {
return new EmailContent.Simple(
applyTemplateData(template.subject(), template.templateData()),
applyTemplateData(template.textPart(), template.templateData()),
applyTemplateData(template.htmlPart(), template.templateData()),
template.headers());
}
static String applyTemplateData(String text, JsonNode data) {
if (text == null || text.isEmpty()) {
return text;
@@ -0,0 +1,45 @@
package io.github.hectorvent.floci.services.ses.model;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
/**
* The body of a send, mirroring the v2 {@code EmailContent} union: exactly one of a simple
* message, a template, or a raw MIME message. A stored template and inline template content are
* separate variants here, since the controllers have already resolved the v2 selector
* (TemplateName, TemplateArn or TemplateContent) by the time a request is built.
*/
public sealed interface EmailContent {
record Simple(String subject, String bodyText, String bodyHtml, List<MessageHeader> headers)
implements EmailContent {
public boolean hasHeaders() {
return headers != null && !headers.isEmpty();
}
public Simple withSafeHeaders() {
if (!hasHeaders()) {
return this;
}
return new Simple(subject, bodyText, bodyHtml, headers.stream().filter(MessageHeader::isSafe).toList());
}
}
record Template(String templateName, JsonNode templateData, List<MessageHeader> headers)
implements EmailContent {
}
record InlineTemplate(String subject, String textPart, String htmlPart, JsonNode templateData,
List<MessageHeader> headers) implements EmailContent {
}
/**
* A raw send reads the envelope's to, cc and bcc as one flat destination list, and falls back
* to the MIME headers when that list is empty. It ignores {@code replyToAddresses}: the
* message carries its own Reply-To header.
*/
record Raw(String data) implements EmailContent {
}
}
@@ -0,0 +1,61 @@
package io.github.hectorvent.floci.services.ses.model;
import java.util.List;
import java.util.Objects;
/**
* The service-level input of a bulk send, shaped like the v2 {@code SendBulkEmailRequest}: an
* envelope, the default template every entry renders, and the per-destination entries. The
* controllers resolve a stored template before building it, so the default content is always
* {@link EmailContent.InlineTemplate}; its data and headers are the defaults each entry's
* replacements merge over.
*/
public record SendBulkEmailRequest(
String source,
List<String> replyToAddresses,
String returnPath,
String configurationSetName,
List<MessageTag> defaultEmailTags,
String tenantName,
String region,
EmailContent.InlineTemplate defaultContent,
List<BulkEmailEntry> entries) {
public SendBulkEmailRequest {
Objects.requireNonNull(defaultContent, "defaultContent");
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private String source;
private List<String> replyToAddresses = List.of();
private String returnPath;
private String configurationSetName;
private List<MessageTag> defaultEmailTags = List.of();
private String tenantName;
private String region;
private EmailContent.InlineTemplate defaultContent;
private List<BulkEmailEntry> entries = List.of();
private Builder() {
}
public Builder source(String source) { this.source = source; return this; }
public Builder replyToAddresses(List<String> replyToAddresses) { this.replyToAddresses = replyToAddresses; return this; }
public Builder returnPath(String returnPath) { this.returnPath = returnPath; return this; }
public Builder configurationSetName(String configurationSetName) { this.configurationSetName = configurationSetName; return this; }
public Builder defaultEmailTags(List<MessageTag> defaultEmailTags) { this.defaultEmailTags = defaultEmailTags; return this; }
public Builder tenantName(String tenantName) { this.tenantName = tenantName; return this; }
public Builder region(String region) { this.region = region; return this; }
public Builder defaultContent(EmailContent.InlineTemplate defaultContent) { this.defaultContent = defaultContent; return this; }
public Builder entries(List<BulkEmailEntry> entries) { this.entries = entries; return this; }
public SendBulkEmailRequest build() {
return new SendBulkEmailRequest(source, replyToAddresses, returnPath, configurationSetName,
defaultEmailTags, tenantName, region, defaultContent, entries);
}
}
}
@@ -0,0 +1,112 @@
package io.github.hectorvent.floci.services.ses.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* The service-level input of a single send, shaped like the v2 {@code SendEmailRequest}: an
* envelope plus an {@link EmailContent}. It is built by the v1 Query handler, the v2 REST
* controller and Cognito, and rebuilt inside SesService whenever the content is rendered or
* sanitized, so the request always carries the content being sent. It is not a wire shape: each
* caller translates its own request into these fields (v2 {@code FromEmailAddress} into
* {@code source}, {@code FeedbackForwardingEmailAddress} into {@code returnPath}, v1 {@code Tags}
* into {@code emailTags}, v1 {@code SendRawEmail} {@code Destinations} into {@code toAddresses}),
* and a field a caller's API lacks keeps the builder default.
*/
public record SendEmailRequest(
String source,
List<String> toAddresses,
List<String> ccAddresses,
List<String> bccAddresses,
List<String> replyToAddresses,
String returnPath,
String configurationSetName,
List<MessageTag> emailTags,
ListManagementOptions listManagement,
String tenantName,
String region,
EmailContent content) {
public SendEmailRequest {
Objects.requireNonNull(content, "content");
}
public List<String> recipients() {
return recipients(toAddresses, ccAddresses, bccAddresses);
}
public static List<String> recipients(List<String> to, List<String> cc, List<String> bcc) {
List<String> all = new ArrayList<>();
if (to != null) {
all.addAll(to);
}
if (cc != null) {
all.addAll(cc);
}
if (bcc != null) {
all.addAll(bcc);
}
return all;
}
public boolean hasRecipients() {
return !recipients().isEmpty();
}
public static Builder builder() {
return new Builder();
}
public Builder toBuilder() {
return new Builder()
.source(source)
.toAddresses(toAddresses)
.ccAddresses(ccAddresses)
.bccAddresses(bccAddresses)
.replyToAddresses(replyToAddresses)
.returnPath(returnPath)
.configurationSetName(configurationSetName)
.emailTags(emailTags)
.listManagement(listManagement)
.tenantName(tenantName)
.region(region)
.content(content);
}
public static final class Builder {
private String source;
private List<String> toAddresses = List.of();
private List<String> ccAddresses = List.of();
private List<String> bccAddresses = List.of();
private List<String> replyToAddresses = List.of();
private String returnPath;
private String configurationSetName;
private List<MessageTag> emailTags = List.of();
private ListManagementOptions listManagement;
private String tenantName;
private String region;
private EmailContent content;
private Builder() {
}
public Builder source(String source) { this.source = source; return this; }
public Builder toAddresses(List<String> toAddresses) { this.toAddresses = toAddresses; return this; }
public Builder ccAddresses(List<String> ccAddresses) { this.ccAddresses = ccAddresses; return this; }
public Builder bccAddresses(List<String> bccAddresses) { this.bccAddresses = bccAddresses; return this; }
public Builder replyToAddresses(List<String> replyToAddresses) { this.replyToAddresses = replyToAddresses; return this; }
public Builder returnPath(String returnPath) { this.returnPath = returnPath; return this; }
public Builder configurationSetName(String configurationSetName) { this.configurationSetName = configurationSetName; return this; }
public Builder emailTags(List<MessageTag> emailTags) { this.emailTags = emailTags; return this; }
public Builder listManagement(ListManagementOptions listManagement) { this.listManagement = listManagement; return this; }
public Builder tenantName(String tenantName) { this.tenantName = tenantName; return this; }
public Builder region(String region) { this.region = region; return this; }
public Builder content(EmailContent content) { this.content = content; return this; }
public SendEmailRequest build() {
return new SendEmailRequest(source, toAddresses, ccAddresses, bccAddresses, replyToAddresses,
returnPath, configurationSetName, emailTags, listManagement, tenantName, region, content);
}
}
}