mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(ses): preserve raw message fidelity and envelope sender in the SMTP relay (#3522)
* feat(ses): preserve raw messages, envelope sender, and X-SES headers in SMTP relay
The raw relay reparsed each MIME message and rebuilt it from the text and
HTML parts alone, dropping every attachment and custom header. It now walks
the Mime4j tree and maps it onto the outgoing message: the first text/plain
and text/html parts become the body, every other leaf becomes an attachment
(inline when it carries a Content-ID, so cid: references still resolve), an
embedded message/rfc822 part is relayed whole, and display names on addresses
survive. Top-level headers are copied through apart from the MIME structural
ones, which the encoder regenerates for the re-built message.
Wire the envelope sender through to MAIL FROM, resolved in AWS's order: the
Return-Path MIME header, then the ReturnPath request field (v1) or
FeedbackForwardingEmailAddress (v2), then the source. The resolved value is
recorded on SentEmail so the inspection endpoint shows it.
Stamp relayed messages with <{MessageId}@{region}.amazonses.com>, matching the
MessageId returned to the caller, leaving a caller-supplied Message-ID alone.
Honour the X-SES-CONFIGURATION-SET and X-SES-MESSAGE-TAGS control headers on
raw sends, which previously parsed to nothing and left event publishing
silently inert for callers using the header form. Both are stripped from the
relayed message, as AWS consumes rather than forwards them. The tenant send
gate sees the same resolved configuration set, so one named only by header
cannot slip past the association check.
Fix tryBase64Decode, which decoded every raw message with the MIME decoder and
only fell back to plain text when it threw. That decoder skips characters
outside the base64 alphabet rather than rejecting them, so a plain-text RFC
5322 message decoded into garbage whenever the surviving alphabet characters
happened to form a valid length, wiping its headers. The alphabet is now
checked before decoding.
Replace the nine-argument SmtpRelay.relay with a RelayMessage record, and add
a ServerSocket-based SMTP test that drives a real MailClient end to end and
asserts on the negotiated envelope and the bytes on the wire, covering the
authentication and STARTTLS-OPTIONAL configuration branches.
* fix(ses): align SMTP relay with documented AWS header and tag semantics
Verified the relay against the SES documentation and corrected four
deviations.
AWS overrides a caller-supplied Message-ID with the id it assigned, and
rejects Message-ID outright as a custom header on Simple and Templated
content (SES header fields reference). The relay preserved a caller's value
instead; it now always stamps the id returned by the API.
AWS likewise overrides a caller-supplied Date with the time it accepted the
message. The relay copied the caller's Date through, so a stale timestamp
reached the recipient. Date is now regenerated with the rest of the headers
SES sets.
AWS uses only the request field's message tags when tags are supplied both
as a request field and as an X-SES-MESSAGE-TAGS header, and explicitly does
not join the two sets. The relay merged them, letting a header-only tag
survive a request that supplied its own. Header tags now apply only when the
request passes none.
The stamped Message-ID domain was region-scoped, which no AWS documentation
or observed output supports. Use the observed email.amazonses.com instead,
and record in the docs that only the local part, which is the returned
MessageId, is documented behaviour.
Also document that AWS delivers a Return-Path differing from the one
supplied, because it routes bounces through its own address, whereas Floci
has no bounce pipeline and puts the resolved address directly in MAIL FROM.
* fix(ses): align mime4j artifacts to unbreak the native build
The raw relay's new DefaultMessageWriter path failed GraalVM analysis with
an unresolved reference to Field.getSafeRaw(). apache-mime4j-dom was pinned
to 0.8.14 while the Quarkus BOM manages apache-mime4j-core at 0.8.12, so the
writer was compiled against a Field API the resolved core does not declare.
Nothing reached the writer before this branch, which is why the skew only
surfaced now, and only in native builds.
Drop the hardcoded -dom version so both artifacts track the BOM together,
and cover the embedded message/rfc822 branch that exercises the writer.
This commit is contained in:
1 parent
325bdfb30e
commit
505b5d286e
17 files changed
+1790
-266
No files matched your search
+1
@@ -71,6 +71,7 @@ public final class CognitoMessageDispatcher {
|
||||
DEFAULT_FROM,
|
||||
List.of(email),
|
||||
List.of(), List.of(), List.of(),
|
||||
null, // returnPath
|
||||
subject,
|
||||
body,
|
||||
null, // bodyHtml
|
||||
|
||||
@@ -479,6 +479,8 @@ public class SesController {
|
||||
List<String> ccAddresses = jsonArrayToList(destination.path("CcAddresses"));
|
||||
List<String> bccAddresses = jsonArrayToList(destination.path("BccAddresses"));
|
||||
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");
|
||||
@@ -502,7 +504,8 @@ public class SesController {
|
||||
sesService.checkTenantRawSendAccess(tenantName, fromEmailAddress, rawData,
|
||||
configurationSetName, regionResolver.getAccountId(), region);
|
||||
messageId = sesService.sendRawEmail(fromEmailAddress, allDestinations, rawData,
|
||||
configurationSetName, emailTags, listManagement, region);
|
||||
feedbackForwardingAddress, configurationSetName, emailTags, listManagement,
|
||||
region);
|
||||
} else if (content.has("Simple")) {
|
||||
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
|
||||
// AWS returns BadRequestException with a null message body here.
|
||||
@@ -517,7 +520,8 @@ public class SesController {
|
||||
sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName,
|
||||
null, regionResolver.getAccountId(), region);
|
||||
messageId = sesService.sendEmail(fromEmailAddress, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, subject, bodyText, bodyHtml,
|
||||
bccAddresses, replyToAddresses, feedbackForwardingAddress,
|
||||
subject, bodyText, bodyHtml,
|
||||
configurationSetName, emailTags, additionalHeaders, listManagement, region);
|
||||
} else if (content.has("Template")) {
|
||||
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
|
||||
@@ -549,7 +553,8 @@ public class SesController {
|
||||
sesService.checkTenantSendAccess(tenantName, fromEmailAddress,
|
||||
configurationSetName, resolvedName, regionResolver.getAccountId(), region);
|
||||
messageId = sesService.sendTemplatedEmail(fromEmailAddress, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, resolvedName, templateData,
|
||||
bccAddresses, replyToAddresses, feedbackForwardingAddress,
|
||||
resolvedName, templateData,
|
||||
configurationSetName, emailTags, additionalHeaders, listManagement, region);
|
||||
} else {
|
||||
JsonNode inline = template.path("TemplateContent");
|
||||
@@ -563,7 +568,7 @@ public class SesController {
|
||||
sesService.checkTenantSendAccess(tenantName, fromEmailAddress,
|
||||
configurationSetName, null, regionResolver.getAccountId(), region);
|
||||
messageId = sesService.sendInlineTemplatedEmail(fromEmailAddress, toAddresses,
|
||||
ccAddresses, bccAddresses, replyToAddresses,
|
||||
ccAddresses, bccAddresses, replyToAddresses, feedbackForwardingAddress,
|
||||
subject, text, html, templateData,
|
||||
configurationSetName, emailTags, additionalHeaders, listManagement, region);
|
||||
}
|
||||
@@ -603,6 +608,8 @@ public class SesController {
|
||||
"FromEmailAddress is required.", 400);
|
||||
}
|
||||
List<String> replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses"));
|
||||
String feedbackForwardingAddress =
|
||||
request.path("FeedbackForwardingEmailAddress").asText(null);
|
||||
String configurationSetName = request.path("ConfigurationSetName").asText(null);
|
||||
String tenantName = stringMemberOrAbsent(request, "TenantName");
|
||||
|
||||
@@ -689,7 +696,7 @@ public class SesController {
|
||||
gateTemplateName, regionResolver.getAccountId(), region);
|
||||
|
||||
List<BulkEmailEntryResult> results = sesService.sendBulkTemplatedEmail(fromEmailAddress,
|
||||
replyToAddresses, subject, text, html,
|
||||
replyToAddresses, feedbackForwardingAddress, subject, text, html,
|
||||
defaultTemplateData, entries, configurationSetName,
|
||||
defaultEmailTags, defaultHeaders, region);
|
||||
|
||||
|
||||
@@ -54,6 +54,9 @@ public class SesInspectionController {
|
||||
node.putNull("Region");
|
||||
}
|
||||
node.put("Source", email.getSource());
|
||||
if (email.getReturnPath() != null) {
|
||||
node.put("ReturnPath", email.getReturnPath());
|
||||
}
|
||||
|
||||
if (email.isRaw()) {
|
||||
// LocalStack returns RawData for raw emails, without
|
||||
|
||||
@@ -226,11 +226,12 @@ public class SesQueryHandler {
|
||||
String bodyText = getParam(params, "Message.Body.Text.Data");
|
||||
String bodyHtml = getParam(params, "Message.Body.Html.Data");
|
||||
String configurationSetName = getParam(params, "ConfigurationSetName");
|
||||
String returnPath = getParam(params, "ReturnPath");
|
||||
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, subject, bodyText, bodyHtml, configurationSetName,
|
||||
replyToAddresses, returnPath, subject, bodyText, bodyHtml, configurationSetName,
|
||||
emailTags, List.of(), null, region);
|
||||
|
||||
String result = new XmlBuilder().elem("MessageId", messageId).build();
|
||||
@@ -249,7 +250,7 @@ public class SesQueryHandler {
|
||||
List<MessageTag> emailTags = extractMessageTags(params, "Tags");
|
||||
|
||||
String messageId = sesService.sendRawEmail(source, destinations, rawMessage,
|
||||
configurationSetName, emailTags, null, region);
|
||||
null, configurationSetName, emailTags, null, region);
|
||||
|
||||
String result = new XmlBuilder().elem("MessageId", messageId).build();
|
||||
return Response.ok(AwsQueryResponse.envelope("SendRawEmail", AwsNamespaces.SES, result)).build();
|
||||
@@ -573,9 +574,10 @@ public class SesQueryHandler {
|
||||
|
||||
JsonNode templateData = parseTemplateData(templateDataRaw);
|
||||
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, resolvedName, templateData,
|
||||
bccAddresses, replyToAddresses, returnPath, resolvedName, templateData,
|
||||
configurationSetName, emailTags, List.of(), null, region);
|
||||
|
||||
String result = new XmlBuilder().elem("MessageId", messageId).build();
|
||||
@@ -715,9 +717,10 @@ 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,
|
||||
template.getSubject(), template.getTextPart(), template.getHtmlPart(),
|
||||
returnPath, template.getSubject(), template.getTextPart(), template.getHtmlPart(),
|
||||
defaultTemplateData, entries, configurationSetName,
|
||||
defaultEmailTags, List.of(), region);
|
||||
|
||||
|
||||
@@ -218,7 +218,7 @@ public class SesService {
|
||||
}
|
||||
|
||||
public String sendEmail(String source, List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses, String returnPath,
|
||||
String subject, String bodyText, String bodyHtml,
|
||||
String configurationSetName, List<MessageTag> emailTags,
|
||||
List<MessageHeader> additionalHeaders, ListManagementOptions listManagement,
|
||||
@@ -264,8 +264,10 @@ public class SesService {
|
||||
}
|
||||
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
String effectiveReturnPath = firstNonBlank(returnPath, source);
|
||||
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);
|
||||
}
|
||||
@@ -275,8 +277,18 @@ public class SesService {
|
||||
List<String> relayedCc = filterUnsuppressed(ccAddresses, suppressedReasons);
|
||||
List<String> relayedBcc = filterUnsuppressed(bccAddresses, suppressedReasons);
|
||||
if (sizeOf(relayedTo) + sizeOf(relayedCc) + sizeOf(relayedBcc) > 0) {
|
||||
smtpRelay.relay(source, relayedTo, relayedCc, relayedBcc,
|
||||
replyToAddresses, subject, bodyText, bodyHtml, additionalHeaders);
|
||||
smtpRelay.relay(SmtpRelay.RelayMessage.builder(source)
|
||||
.returnPath(effectiveReturnPath)
|
||||
.to(relayedTo)
|
||||
.cc(relayedCc)
|
||||
.bcc(relayedBcc)
|
||||
.replyTo(replyToAddresses)
|
||||
.subject(subject)
|
||||
.bodyText(bodyText)
|
||||
.bodyHtml(bodyHtml)
|
||||
.headers(additionalHeaders)
|
||||
.messageId(messageId)
|
||||
.build());
|
||||
} else {
|
||||
LOG.infov("SES email accepted but not relayed (all recipients suppressed): messageId={0}",
|
||||
messageId);
|
||||
@@ -291,21 +303,29 @@ public class SesService {
|
||||
}
|
||||
|
||||
public String sendRawEmail(String source, List<String> destinations, String rawMessage,
|
||||
String configurationSetName, List<MessageTag> emailTags,
|
||||
String returnPath, String configurationSetName, List<MessageTag> emailTags,
|
||||
ListManagementOptions listManagement, String region) {
|
||||
if (rawMessage == null || rawMessage.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "RawMessage.Data is required.", 400);
|
||||
}
|
||||
String effectiveConfigSet = resolveDefaultConfigurationSet(configurationSetName, source, region);
|
||||
configSetService.validateForSending(effectiveConfigSet, region);
|
||||
boolean hasExplicitDestinations = destinations != null && !destinations.isEmpty();
|
||||
boolean sourceOmitted = source == null || source.isBlank();
|
||||
boolean willPublishEvents = (effectiveConfigSet != null && !effectiveConfigSet.isBlank())
|
||||
|| !resolveIdentityNotificationTargets(source, region).isEmpty();
|
||||
SmtpRelay.RawMessageHeaders headers = (hasExplicitDestinations && !willPublishEvents && !sourceOmitted)
|
||||
? null
|
||||
: SmtpRelay.parseRawHeaders(rawMessage);
|
||||
String effectiveSource = sourceOmitted && headers != null && !headers.from().isBlank()
|
||||
// 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.RawMessageHeaders headers = SmtpRelay.parseRawHeaders(rawMessage);
|
||||
// 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 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())
|
||||
? headers.messageTags()
|
||||
: emailTags;
|
||||
String effectiveSource = sourceOmitted && !headers.from().isBlank()
|
||||
? headers.from()
|
||||
: source;
|
||||
if (effectiveSource == null || effectiveSource.isBlank()) {
|
||||
@@ -319,8 +339,8 @@ public class SesService {
|
||||
// sender until the MIME "From" was parsed. Re-resolve from the effective sender now so an
|
||||
// email identity's default configuration set still applies to a Raw send without an
|
||||
// explicit FromEmailAddress.
|
||||
if (sourceOmitted && (configurationSetName == null || configurationSetName.isBlank())) {
|
||||
effectiveConfigSet = resolveDefaultConfigurationSet(configurationSetName, effectiveSource, region);
|
||||
if (sourceOmitted && (requestedConfigSet == null || requestedConfigSet.isBlank())) {
|
||||
effectiveConfigSet = resolveDefaultConfigurationSet(requestedConfigSet, effectiveSource, region);
|
||||
configSetService.validateForSending(effectiveConfigSet, region);
|
||||
}
|
||||
List<String> effectiveDestinations = hasExplicitDestinations
|
||||
@@ -341,12 +361,17 @@ public class SesService {
|
||||
.forEach(suppressedReasons::putIfAbsent);
|
||||
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
// AWS routes bounces to the Return-Path carried by the message, falling back to the
|
||||
// request's return path and then the sender.
|
||||
String effectiveReturnPath = firstNonBlank(headers.returnPath(), returnPath, effectiveSource);
|
||||
SentEmail email = new SentEmail(messageId, region, effectiveSource, effectiveDestinations, rawMessage);
|
||||
email.setReturnPath(effectiveReturnPath);
|
||||
sentEmailService.record(region, messageId, email);
|
||||
|
||||
List<String> relayedDestinations = filterUnsuppressed(effectiveDestinations, suppressedReasons);
|
||||
if (!relayedDestinations.isEmpty()) {
|
||||
smtpRelay.relayRaw(effectiveSource, relayedDestinations, rawMessage);
|
||||
smtpRelay.relayRaw(new SmtpRelay.RawRelayMessage(effectiveSource, effectiveReturnPath,
|
||||
relayedDestinations, rawMessage, messageId));
|
||||
} else {
|
||||
LOG.infov("SES raw email accepted but not relayed (all recipients suppressed): messageId={0}",
|
||||
messageId);
|
||||
@@ -354,12 +379,9 @@ public class SesService {
|
||||
|
||||
LOG.infov("SES raw email sent: from={0}, messageId={1}", effectiveSource, messageId);
|
||||
publishSendEvents(effectiveConfigSet, messageId, effectiveSource,
|
||||
headers != null ? headers.subject() : "",
|
||||
headers != null ? headers.to() : List.of(),
|
||||
headers != null ? headers.cc() : List.of(),
|
||||
headers != null ? headers.bcc() : List.of(),
|
||||
headers.subject(), headers.to(), headers.cc(), headers.bcc(),
|
||||
effectiveDestinations,
|
||||
suppressedReasons, emailTags, List.of(), region);
|
||||
suppressedReasons, effectiveTags, List.of(), region);
|
||||
return messageId;
|
||||
}
|
||||
|
||||
@@ -803,9 +825,19 @@ public class SesService {
|
||||
SentEmail email = new SentEmail(messageId, region, template.getFromEmailAddress(),
|
||||
List.of(emailAddress), List.of(), List.of(), List.of(),
|
||||
template.getTemplateSubject(), null, renderedHtml);
|
||||
email.setReturnPath(template.getFromEmailAddress());
|
||||
sentEmailService.record(region, messageId, email);
|
||||
smtpRelay.relay(template.getFromEmailAddress(), List.of(emailAddress), List.of(), List.of(),
|
||||
List.of(), template.getTemplateSubject(), null, renderedHtml, List.of());
|
||||
smtpRelay.relay(SmtpRelay.RelayMessage.builder(template.getFromEmailAddress())
|
||||
.returnPath(template.getFromEmailAddress())
|
||||
.to(List.of(emailAddress))
|
||||
.cc(List.of())
|
||||
.bcc(List.of())
|
||||
.replyTo(List.of())
|
||||
.subject(template.getTemplateSubject())
|
||||
.bodyHtml(renderedHtml)
|
||||
.headers(List.of())
|
||||
.messageId(messageId)
|
||||
.build());
|
||||
LOG.infov("SES custom verification email sent: to={0}, template={1}, messageId={2}",
|
||||
emailAddress, templateName, messageId);
|
||||
return messageId;
|
||||
@@ -1069,12 +1101,15 @@ public class SesService {
|
||||
if (tenantName == null) {
|
||||
return;
|
||||
}
|
||||
SmtpRelay.RawMessageHeaders headers = SmtpRelay.parseRawHeaders(rawMessage);
|
||||
String effectiveSource = fromEmailAddress;
|
||||
if (effectiveSource == null || effectiveSource.isBlank()) {
|
||||
SmtpRelay.RawMessageHeaders headers = SmtpRelay.parseRawHeaders(rawMessage);
|
||||
effectiveSource = headers != null && !headers.from().isBlank() ? headers.from() : null;
|
||||
effectiveSource = headers.from().isBlank() ? null : headers.from();
|
||||
}
|
||||
checkTenantSendAccess(tenantName, effectiveSource, configurationSetName, null,
|
||||
// The gate sees the same configuration set the send will use, so one named only by the
|
||||
// X-SES-CONFIGURATION-SET header cannot slip past the tenant association check.
|
||||
checkTenantSendAccess(tenantName, effectiveSource,
|
||||
firstNonBlank(configurationSetName, headers.configurationSet()), null,
|
||||
accountId, region);
|
||||
}
|
||||
|
||||
@@ -1780,13 +1815,13 @@ public class SesService {
|
||||
|
||||
public String sendTemplatedEmail(String source, List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses,
|
||||
String templateName, JsonNode templateData,
|
||||
String returnPath, String templateName, JsonNode templateData,
|
||||
String configurationSetName, List<MessageTag> emailTags,
|
||||
List<MessageHeader> additionalHeaders,
|
||||
ListManagementOptions listManagement, String region) {
|
||||
EmailTemplate template = getTemplate(templateName, region);
|
||||
return sendInlineTemplatedEmail(source, toAddresses, ccAddresses, bccAddresses,
|
||||
replyToAddresses, template.getSubject(), template.getTextPart(),
|
||||
replyToAddresses, returnPath, template.getSubject(), template.getTextPart(),
|
||||
template.getHtmlPart(), templateData,
|
||||
configurationSetName, emailTags, additionalHeaders, listManagement, region);
|
||||
}
|
||||
@@ -1812,13 +1847,14 @@ 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 region) {
|
||||
requireInlineTemplateContent(subject, textPart, htmlPart);
|
||||
return sendEmail(source, toAddresses, ccAddresses, bccAddresses, replyToAddresses,
|
||||
return sendEmail(source, toAddresses, ccAddresses, bccAddresses, replyToAddresses, returnPath,
|
||||
SesTemplateService.applyTemplateData(subject, templateData),
|
||||
SesTemplateService.applyTemplateData(textPart, templateData),
|
||||
SesTemplateService.applyTemplateData(htmlPart, templateData),
|
||||
@@ -1827,6 +1863,7 @@ public class SesService {
|
||||
|
||||
public List<BulkEmailEntryResult> sendBulkTemplatedEmail(String source,
|
||||
List<String> replyToAddresses,
|
||||
String returnPath,
|
||||
String subject, String textPart, String htmlPart,
|
||||
JsonNode defaultTemplateData,
|
||||
List<BulkEmailEntry> entries,
|
||||
@@ -1869,7 +1906,7 @@ public class SesService {
|
||||
// does not apply to bulk sends.
|
||||
String messageId = sendEmail(source,
|
||||
entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses(),
|
||||
replyToAddresses,
|
||||
replyToAddresses, returnPath,
|
||||
SesTemplateService.applyTemplateData(subject, merged),
|
||||
SesTemplateService.applyTemplateData(textPart, merged),
|
||||
SesTemplateService.applyTemplateData(htmlPart, merged),
|
||||
@@ -1889,6 +1926,15 @@ public class SesService {
|
||||
return list == null ? 0 : list.size();
|
||||
}
|
||||
|
||||
private static String firstNonBlank(String... values) {
|
||||
for (String value : values) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static BulkEmailEntryResult.Status mapErrorCodeToBulkStatus(String errorCode) {
|
||||
if ("InvalidParameterValue".equals(errorCode)
|
||||
|| "MissingRenderingAttribute".equals(errorCode)
|
||||
|
||||
@@ -2,6 +2,9 @@ package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageTag;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.ext.mail.MailAttachment;
|
||||
import io.vertx.ext.mail.MailClient;
|
||||
import io.vertx.ext.mail.MailConfig;
|
||||
import io.vertx.ext.mail.MailMessage;
|
||||
@@ -11,19 +14,30 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.james.mime4j.dom.Body;
|
||||
import org.apache.james.mime4j.dom.Entity;
|
||||
import org.apache.james.mime4j.dom.Header;
|
||||
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.dom.TextBody;
|
||||
import org.apache.james.mime4j.dom.address.Mailbox;
|
||||
import org.apache.james.mime4j.dom.address.MailboxList;
|
||||
import org.apache.james.mime4j.dom.field.FieldName;
|
||||
import org.apache.james.mime4j.field.address.AddressFormatter;
|
||||
import org.apache.james.mime4j.message.DefaultMessageBuilder;
|
||||
import org.apache.james.mime4j.message.DefaultMessageWriter;
|
||||
import org.apache.james.mime4j.stream.Field;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.AbstractExecutorService;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -44,6 +58,31 @@ public class SmtpRelay {
|
||||
private static final Logger LOG = Logger.getLogger(SmtpRelay.class);
|
||||
private static final long RELAY_TIMEOUT_SECONDS = 30;
|
||||
|
||||
/** SES control header naming the configuration set to apply to a raw send. */
|
||||
public static final String HEADER_CONFIGURATION_SET = "X-SES-CONFIGURATION-SET";
|
||||
/** SES control header carrying {@code name=value} message tags for a raw send. */
|
||||
public static final String HEADER_MESSAGE_TAGS = "X-SES-MESSAGE-TAGS";
|
||||
|
||||
private static final String X_SES_PREFIX = "x-ses-";
|
||||
private static final String HEADER_RETURN_PATH = "Return-Path";
|
||||
private static final String MESSAGE_ID_DOMAIN = "email.amazonses.com";
|
||||
|
||||
/**
|
||||
* Top-level headers of a raw message that are not copied onto the relayed message. The MIME
|
||||
* structural headers are regenerated by the Vert.x encoder for the re-built message, so passing
|
||||
* the originals through would announce a content type and boundary that no longer describe the
|
||||
* body. The address and subject headers are set on {@link MailMessage} directly, and
|
||||
* {@code Return-Path} becomes the envelope sender (the receiving MTA writes its own).
|
||||
*
|
||||
* <p>{@code Date} and {@code Message-ID} are excluded because AWS overrides both: a caller's
|
||||
* {@code Date} is replaced with the time the message was accepted, and a caller's
|
||||
* {@code Message-ID} with the id SES assigned (SES header fields reference).
|
||||
*/
|
||||
private static final Set<String> SUPPRESSED_RELAY_HEADERS = Set.of(
|
||||
"mime-version", "content-type", "content-transfer-encoding",
|
||||
"content-disposition", "content-id",
|
||||
"from", "to", "cc", "bcc", "subject", "return-path", "message-id", "date");
|
||||
|
||||
private final MailClient mailClient;
|
||||
private final ExecutorService relayExecutor;
|
||||
private final boolean enabled;
|
||||
@@ -64,35 +103,39 @@ public class SmtpRelay {
|
||||
int port = config.services().ses().smtpPort();
|
||||
LOG.infov("SES SMTP relay enabled: {0}:{1}", host, String.valueOf(port));
|
||||
|
||||
MailConfig mailConfig = new MailConfig()
|
||||
.setHostname(host)
|
||||
.setPort(port);
|
||||
config.services().ses().smtpUser()
|
||||
.filter(u -> !u.isBlank())
|
||||
.ifPresent(u -> {
|
||||
mailConfig.setUsername(u);
|
||||
config.services().ses().smtpPass()
|
||||
.filter(p -> !p.isBlank())
|
||||
.ifPresent(mailConfig::setPassword);
|
||||
});
|
||||
String starttls = config.services().ses().smtpStarttls();
|
||||
if ("REQUIRED".equalsIgnoreCase(starttls)) {
|
||||
mailConfig.setStarttls(StartTLSOptions.REQUIRED);
|
||||
} else if ("OPTIONAL".equalsIgnoreCase(starttls)) {
|
||||
mailConfig.setStarttls(StartTLSOptions.OPTIONAL);
|
||||
} else {
|
||||
if (!"DISABLED".equalsIgnoreCase(starttls)) {
|
||||
LOG.warnv("Unrecognized smtp-starttls value \"{0}\", defaulting to DISABLED", starttls);
|
||||
}
|
||||
mailConfig.setStarttls(StartTLSOptions.DISABLED);
|
||||
}
|
||||
this.mailClient = MailClient.create(vertx, mailConfig);
|
||||
this.mailClient = MailClient.create(vertx, buildMailConfig(config, host, port));
|
||||
} else {
|
||||
this.relayExecutor = null;
|
||||
this.mailClient = null;
|
||||
}
|
||||
}
|
||||
|
||||
static MailConfig buildMailConfig(EmulatorConfig config, String host, int port) {
|
||||
MailConfig mailConfig = new MailConfig()
|
||||
.setHostname(host)
|
||||
.setPort(port);
|
||||
config.services().ses().smtpUser()
|
||||
.filter(u -> !u.isBlank())
|
||||
.ifPresent(u -> {
|
||||
mailConfig.setUsername(u);
|
||||
config.services().ses().smtpPass()
|
||||
.filter(p -> !p.isBlank())
|
||||
.ifPresent(mailConfig::setPassword);
|
||||
});
|
||||
String starttls = config.services().ses().smtpStarttls();
|
||||
if ("REQUIRED".equalsIgnoreCase(starttls)) {
|
||||
mailConfig.setStarttls(StartTLSOptions.REQUIRED);
|
||||
} else if ("OPTIONAL".equalsIgnoreCase(starttls)) {
|
||||
mailConfig.setStarttls(StartTLSOptions.OPTIONAL);
|
||||
} else {
|
||||
if (!"DISABLED".equalsIgnoreCase(starttls)) {
|
||||
LOG.warnv("Unrecognized smtp-starttls value \"{0}\", defaulting to DISABLED", starttls);
|
||||
}
|
||||
mailConfig.setStarttls(StartTLSOptions.DISABLED);
|
||||
}
|
||||
return mailConfig;
|
||||
}
|
||||
|
||||
/** Package-private constructor for tests (synchronous executor, mock client). */
|
||||
SmtpRelay(MailClient mailClient, boolean enabled) {
|
||||
this.mailClient = mailClient;
|
||||
@@ -123,155 +166,399 @@ public class SmtpRelay {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* A structured (non-raw) message to relay. Built with {@link #builder(String)}; every field
|
||||
* other than the sender is optional.
|
||||
*/
|
||||
public record RelayMessage(String from, String returnPath,
|
||||
List<String> to, List<String> cc, List<String> bcc,
|
||||
List<String> replyTo,
|
||||
String subject, String bodyText, String bodyHtml,
|
||||
List<MessageHeader> headers,
|
||||
String messageId) {
|
||||
|
||||
public static Builder builder(String from) {
|
||||
return new Builder(from);
|
||||
}
|
||||
|
||||
public static final class Builder {
|
||||
private final String from;
|
||||
private String returnPath;
|
||||
private List<String> to;
|
||||
private List<String> cc;
|
||||
private List<String> bcc;
|
||||
private List<String> replyTo;
|
||||
private String subject;
|
||||
private String bodyText;
|
||||
private String bodyHtml;
|
||||
private List<MessageHeader> headers;
|
||||
private String messageId;
|
||||
|
||||
private Builder(String from) {
|
||||
this.from = from;
|
||||
}
|
||||
|
||||
public Builder returnPath(String returnPath) { this.returnPath = returnPath; return this; }
|
||||
public Builder to(List<String> to) { this.to = to; return this; }
|
||||
public Builder cc(List<String> cc) { this.cc = cc; return this; }
|
||||
public Builder bcc(List<String> bcc) { this.bcc = bcc; return this; }
|
||||
public Builder replyTo(List<String> replyTo) { this.replyTo = replyTo; return this; }
|
||||
public Builder subject(String subject) { this.subject = subject; return this; }
|
||||
public Builder bodyText(String bodyText) { this.bodyText = bodyText; return this; }
|
||||
public Builder bodyHtml(String bodyHtml) { this.bodyHtml = bodyHtml; return this; }
|
||||
public Builder headers(List<MessageHeader> headers) { this.headers = headers; return this; }
|
||||
public Builder messageId(String messageId) { this.messageId = messageId; return this; }
|
||||
|
||||
public RelayMessage build() {
|
||||
return new RelayMessage(from, returnPath, to, cc, bcc, replyTo,
|
||||
subject, bodyText, bodyHtml, headers, messageId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A raw RFC 5322 message to relay verbatim. {@code destinations} is the envelope recipient
|
||||
* list; when empty the MIME To / Cc / Bcc headers are used instead.
|
||||
*/
|
||||
public record RawRelayMessage(String from, String returnPath, List<String> destinations,
|
||||
String rawMessage, String messageId) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Relays a structured email asynchronously.
|
||||
*/
|
||||
public void relay(String from, List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses,
|
||||
String subject, String bodyText, String bodyHtml,
|
||||
List<MessageHeader> additionalHeaders) {
|
||||
public void relay(RelayMessage message) {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
relayExecutor.execute(() -> doRelay(from, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, subject, bodyText, bodyHtml, additionalHeaders));
|
||||
relayExecutor.execute(() -> doRelay(message));
|
||||
} catch (java.util.concurrent.RejectedExecutionException e) {
|
||||
LOG.warnv("SMTP relay skipped (executor shutting down) for from={0}", from);
|
||||
LOG.warnv("SMTP relay skipped (executor shutting down) for from={0}", message.from());
|
||||
}
|
||||
}
|
||||
|
||||
private void doRelay(String from, List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses,
|
||||
String subject, String bodyText, String bodyHtml,
|
||||
List<MessageHeader> additionalHeaders) {
|
||||
private void doRelay(RelayMessage message) {
|
||||
try {
|
||||
MailMessage mail = new MailMessage();
|
||||
mail.setFrom(from);
|
||||
if (toAddresses != null) {
|
||||
mail.setTo(toAddresses);
|
||||
mail.setFrom(message.from());
|
||||
applyBounceAddress(mail, message.returnPath(), message.from());
|
||||
if (message.to() != null) {
|
||||
mail.setTo(message.to());
|
||||
}
|
||||
if (ccAddresses != null) {
|
||||
mail.setCc(ccAddresses);
|
||||
if (message.cc() != null) {
|
||||
mail.setCc(message.cc());
|
||||
}
|
||||
if (bccAddresses != null) {
|
||||
mail.setBcc(bccAddresses);
|
||||
if (message.bcc() != null) {
|
||||
mail.setBcc(message.bcc());
|
||||
}
|
||||
if (replyToAddresses != null && !replyToAddresses.isEmpty()) {
|
||||
mail.addHeader("Reply-To", String.join(", ", replyToAddresses));
|
||||
if (message.replyTo() != null && !message.replyTo().isEmpty()) {
|
||||
mail.addHeader("Reply-To", String.join(", ", message.replyTo()));
|
||||
}
|
||||
if (additionalHeaders != null) {
|
||||
for (MessageHeader header : additionalHeaders) {
|
||||
if (header.isSafe()) {
|
||||
mail.addHeader(header.name(), header.value());
|
||||
} else {
|
||||
if (message.headers() != null) {
|
||||
for (MessageHeader header : message.headers()) {
|
||||
if (!header.isSafe()) {
|
||||
LOG.warnv("SMTP relay: skipping a header with a blank name or CR/LF in its "
|
||||
+ "name/value (possible header injection) for from={0}", from);
|
||||
+ "name/value (possible header injection) for from={0}", message.from());
|
||||
continue;
|
||||
}
|
||||
if (FieldName.MESSAGE_ID.equalsIgnoreCase(header.name())) {
|
||||
// AWS overrides a caller-supplied Message-ID, and rejects it outright as a
|
||||
// custom header on Simple / Templated content.
|
||||
continue;
|
||||
}
|
||||
mail.addHeader(header.name(), header.value());
|
||||
}
|
||||
}
|
||||
mail.setSubject(subject != null ? subject : "");
|
||||
if (bodyText != null) {
|
||||
mail.setText(bodyText);
|
||||
applyMessageId(mail, message.messageId());
|
||||
mail.setSubject(message.subject() != null ? message.subject() : "");
|
||||
if (message.bodyText() != null) {
|
||||
mail.setText(message.bodyText());
|
||||
}
|
||||
if (bodyHtml != null) {
|
||||
mail.setHtml(bodyHtml);
|
||||
if (message.bodyHtml() != null) {
|
||||
mail.setHtml(message.bodyHtml());
|
||||
}
|
||||
|
||||
mailClient.sendMail(mail).toCompletionStage().toCompletableFuture().get(RELAY_TIMEOUT_SECONDS, java.util.concurrent.TimeUnit.SECONDS);
|
||||
LOG.debugv("SMTP relay: sent from={0}, to={1}, subject={2}", from, toAddresses, subject);
|
||||
send(mail);
|
||||
LOG.debugv("SMTP relay: sent from={0}, to={1}, subject={2}",
|
||||
message.from(), message.to(), message.subject());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warnv(e, "SMTP relay interrupted for from={0}, to={1}", from, toAddresses);
|
||||
LOG.warnv(e, "SMTP relay interrupted for from={0}, to={1}", message.from(), message.to());
|
||||
} catch (java.util.concurrent.TimeoutException e) {
|
||||
LOG.warnv("SMTP relay timed out after {0}s for from={1}, to={2}", RELAY_TIMEOUT_SECONDS, from, toAddresses);
|
||||
LOG.warnv("SMTP relay timed out after {0}s for from={1}, to={2}",
|
||||
RELAY_TIMEOUT_SECONDS, message.from(), message.to());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "SMTP relay failed for from={0}, to={1}", from, toAddresses);
|
||||
LOG.warnv(e, "SMTP relay failed for from={0}, to={1}", message.from(), message.to());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Relays a raw MIME message. Parsed with Mime4j, then sent via MailClient.
|
||||
*/
|
||||
public void relayRaw(String from, List<String> destinations, String rawMessage) {
|
||||
public void relayRaw(RawRelayMessage message) {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
relayExecutor.execute(() -> doRelayRaw(from, destinations, rawMessage));
|
||||
relayExecutor.execute(() -> doRelayRaw(message));
|
||||
} catch (java.util.concurrent.RejectedExecutionException e) {
|
||||
LOG.warnv("SMTP raw relay skipped (executor shutting down) for from={0}", from);
|
||||
LOG.warnv("SMTP raw relay skipped (executor shutting down) for from={0}", message.from());
|
||||
}
|
||||
}
|
||||
|
||||
private void doRelayRaw(String from, List<String> destinations, String rawMessage) {
|
||||
private void doRelayRaw(RawRelayMessage relayMessage) {
|
||||
try {
|
||||
byte[] mimeBytes = tryBase64Decode(rawMessage);
|
||||
byte[] mimeBytes = tryBase64Decode(relayMessage.rawMessage());
|
||||
var builder = new DefaultMessageBuilder();
|
||||
var message = builder.parseMessage(new ByteArrayInputStream(mimeBytes));
|
||||
|
||||
MailMessage mail = new MailMessage();
|
||||
|
||||
// From
|
||||
// From. The display name is kept, so "Alice <alice@example.com>" is delivered as the
|
||||
// caller wrote it rather than as a bare address.
|
||||
if (message.getFrom() != null && !message.getFrom().isEmpty()) {
|
||||
mail.setFrom(message.getFrom().get(0).getAddress());
|
||||
mail.setFrom(formatMailbox(message.getFrom().get(0)));
|
||||
} else {
|
||||
mail.setFrom(from);
|
||||
mail.setFrom(relayMessage.from());
|
||||
}
|
||||
applyBounceAddress(mail, relayMessage.returnPath(), mail.getFrom());
|
||||
|
||||
// SES SendRawEmail: when Destinations is provided, it is the
|
||||
// authoritative envelope recipient list — MIME To/Cc headers are
|
||||
// display-only and must not add extra SMTP RCPT TO entries.
|
||||
List<String> destinations = relayMessage.destinations();
|
||||
if (destinations != null && !destinations.isEmpty()) {
|
||||
mail.setTo(destinations);
|
||||
} else {
|
||||
MailboxList toList = message.getTo() != null ? message.getTo().flatten() : null;
|
||||
if (toList != null && !toList.isEmpty()) {
|
||||
mail.setTo(toMailboxAddresses(toList));
|
||||
mail.setTo(formatMailboxes(toList));
|
||||
}
|
||||
MailboxList ccList = message.getCc() != null ? message.getCc().flatten() : null;
|
||||
if (ccList != null && !ccList.isEmpty()) {
|
||||
mail.setCc(toMailboxAddresses(ccList));
|
||||
mail.setCc(formatMailboxes(ccList));
|
||||
}
|
||||
MailboxList bccList = message.getBcc() != null ? message.getBcc().flatten() : null;
|
||||
if (bccList != null && !bccList.isEmpty()) {
|
||||
mail.setBcc(toMailboxAddresses(bccList));
|
||||
mail.setBcc(formatMailboxes(bccList));
|
||||
}
|
||||
}
|
||||
|
||||
// Subject
|
||||
mail.setSubject(message.getSubject() != null ? message.getSubject() : "");
|
||||
|
||||
// Body
|
||||
extractBodyFromEntity(message, mail);
|
||||
applyMimeParts(message, mail);
|
||||
copyRawHeaders(message, mail);
|
||||
applyMessageId(mail, relayMessage.messageId());
|
||||
|
||||
mailClient.sendMail(mail).toCompletionStage().toCompletableFuture().get(RELAY_TIMEOUT_SECONDS, java.util.concurrent.TimeUnit.SECONDS);
|
||||
LOG.debugv("SMTP relay: sent raw from={0}, destinations={1}", from, destinations);
|
||||
send(mail);
|
||||
LOG.debugv("SMTP relay: sent raw from={0}, destinations={1}",
|
||||
relayMessage.from(), relayMessage.destinations());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warnv(e, "SMTP raw relay interrupted for from={0}", from);
|
||||
LOG.warnv(e, "SMTP raw relay interrupted for from={0}", relayMessage.from());
|
||||
} catch (java.util.concurrent.TimeoutException e) {
|
||||
LOG.warnv("SMTP raw relay timed out after {0}s for from={1}", RELAY_TIMEOUT_SECONDS, from);
|
||||
LOG.warnv("SMTP raw relay timed out after {0}s for from={1}",
|
||||
RELAY_TIMEOUT_SECONDS, relayMessage.from());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "SMTP raw relay failed for from={0}", from);
|
||||
LOG.warnv(e, "SMTP raw relay failed for from={0}", relayMessage.from());
|
||||
}
|
||||
}
|
||||
|
||||
private static void extractBodyFromEntity(Entity entity, MailMessage mail) {
|
||||
private void send(MailMessage mail) throws Exception {
|
||||
mailClient.sendMail(mail).toCompletionStage().toCompletableFuture()
|
||||
.get(RELAY_TIMEOUT_SECONDS, java.util.concurrent.TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private static void applyBounceAddress(MailMessage mail, String returnPath, String fallback) {
|
||||
String bounce = firstNonBlank(returnPath, fallback);
|
||||
if (bounce != null) {
|
||||
mail.setBounceAddress(extractAngleAddress(bounce));
|
||||
}
|
||||
}
|
||||
|
||||
private static void applyMessageId(MailMessage mail, String messageId) {
|
||||
String header = formatMessageId(messageId);
|
||||
if (header != null) {
|
||||
mail.addHeader(FieldName.MESSAGE_ID, header);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats the Message-ID that AWS stamps on the delivered message. AWS documents that it
|
||||
* overrides any caller-supplied Message-ID with its own value, and that the id it assigns is
|
||||
* the {@code MessageId} returned to the caller; the local part here is therefore that id. The
|
||||
* {@code @email.amazonses.com} domain is not documented and follows observed SES output.
|
||||
* Returns null when there is no id to stamp.
|
||||
*/
|
||||
static String formatMessageId(String messageId) {
|
||||
if (messageId == null || messageId.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return "<" + messageId + "@" + MESSAGE_ID_DOMAIN + ">";
|
||||
}
|
||||
|
||||
// ──────────────────────────── Raw MIME walking ────────────────────────────
|
||||
|
||||
/** Text bodies and attachments collected from one raw MIME tree. */
|
||||
private static final class MimeParts {
|
||||
private String text;
|
||||
private String html;
|
||||
private final List<MailAttachment> attachments = new ArrayList<>();
|
||||
private final List<MailAttachment> inline = new ArrayList<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps the parsed MIME tree onto the outgoing message: the first text/plain and text/html
|
||||
* parts become the body, every other leaf becomes an attachment. Parts carrying a
|
||||
* {@code Content-ID} are relayed as inline attachments so {@code cid:} references in the HTML
|
||||
* body still resolve.
|
||||
*/
|
||||
private static void applyMimeParts(Message message, MailMessage mail) {
|
||||
MimeParts parts = new MimeParts();
|
||||
collectParts(message, parts);
|
||||
if (parts.text != null) {
|
||||
mail.setText(parts.text);
|
||||
}
|
||||
if (parts.html != null) {
|
||||
mail.setHtml(parts.html);
|
||||
}
|
||||
List<MailAttachment> attachments = new ArrayList<>(parts.attachments);
|
||||
if (parts.html != null && !parts.inline.isEmpty()) {
|
||||
mail.setInlineAttachment(parts.inline);
|
||||
} else {
|
||||
// The Vert.x encoder only emits inline attachments alongside an HTML body, so without
|
||||
// one they would be dropped silently. Relay them as regular attachments instead.
|
||||
attachments.addAll(parts.inline);
|
||||
}
|
||||
if (!attachments.isEmpty()) {
|
||||
mail.setAttachment(attachments);
|
||||
}
|
||||
}
|
||||
|
||||
private static void collectParts(Entity entity, MimeParts parts) {
|
||||
Body body = entity.getBody();
|
||||
if (body instanceof TextBody textBody) {
|
||||
// Keep the first text/plain and text/html parts encountered so that a
|
||||
// text-typed attachment later in a multipart/mixed message cannot
|
||||
// clobber the body already picked up from multipart/alternative.
|
||||
if ("text/html".equalsIgnoreCase(entity.getMimeType()) && mail.getHtml() == null) {
|
||||
mail.setHtml(readTextBody(textBody));
|
||||
} else if ("text/plain".equalsIgnoreCase(entity.getMimeType()) && mail.getText() == null) {
|
||||
mail.setText(readTextBody(textBody));
|
||||
}
|
||||
} else if (body instanceof Multipart multipart) {
|
||||
if (body instanceof Multipart multipart) {
|
||||
for (Entity part : multipart.getBodyParts()) {
|
||||
extractBodyFromEntity(part, mail);
|
||||
collectParts(part, parts);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (body instanceof TextBody textBody && !isAttachmentPart(entity)) {
|
||||
// Keep the first text/plain and text/html parts encountered so that a second one later
|
||||
// in a multipart/mixed message cannot clobber the body already picked up from
|
||||
// multipart/alternative.
|
||||
String mimeType = entity.getMimeType();
|
||||
if ("text/html".equalsIgnoreCase(mimeType)) {
|
||||
if (parts.html == null) {
|
||||
parts.html = readTextBody(textBody);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if ("text/plain".equalsIgnoreCase(mimeType)) {
|
||||
if (parts.text == null) {
|
||||
parts.text = readTextBody(textBody);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
MailAttachment attachment = toAttachment(entity, body);
|
||||
if (attachment == null) {
|
||||
return;
|
||||
}
|
||||
if (attachment.getContentId() != null) {
|
||||
parts.inline.add(attachment);
|
||||
} else {
|
||||
parts.attachments.add(attachment);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isAttachmentPart(Entity entity) {
|
||||
return "attachment".equalsIgnoreCase(entity.getDispositionType())
|
||||
|| entity.getFilename() != null
|
||||
|| headerValue(entity, FieldName.CONTENT_ID) != null;
|
||||
}
|
||||
|
||||
private static MailAttachment toAttachment(Entity entity, Body body) {
|
||||
byte[] data = readBodyBytes(body);
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
MailAttachment attachment = MailAttachment.create()
|
||||
.setData(Buffer.buffer(data))
|
||||
.setContentType(attachmentContentType(entity))
|
||||
.setName(entity.getFilename());
|
||||
String disposition = entity.getDispositionType();
|
||||
if (disposition != null && !disposition.isBlank()) {
|
||||
attachment.setDisposition(disposition);
|
||||
}
|
||||
String description = headerValue(entity, FieldName.CONTENT_DESCRIPTION);
|
||||
if (description != null) {
|
||||
attachment.setDescription(description);
|
||||
}
|
||||
String contentId = headerValue(entity, FieldName.CONTENT_ID);
|
||||
if (contentId != null) {
|
||||
attachment.setContentId(contentId);
|
||||
}
|
||||
return attachment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decoded bytes of a leaf part. An embedded message/rfc822 part is re-serialized whole so a
|
||||
* forwarded message survives the relay.
|
||||
*/
|
||||
private static byte[] readBodyBytes(Body body) {
|
||||
try {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
if (body instanceof SingleBody singleBody) {
|
||||
singleBody.writeTo(out);
|
||||
} else if (body instanceof Message embedded) {
|
||||
new DefaultMessageWriter().writeMessage(embedded, out);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
return out.toByteArray();
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "SMTP raw relay: could not read a MIME part, dropping it");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String attachmentContentType(Entity entity) {
|
||||
String mimeType = entity.getMimeType();
|
||||
if (mimeType == null || mimeType.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String charset = entity.getCharset();
|
||||
if (charset != null && !charset.isBlank()
|
||||
&& mimeType.toLowerCase(Locale.ROOT).startsWith("text/")) {
|
||||
return mimeType + "; charset=" + charset;
|
||||
}
|
||||
return mimeType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the caller's top-level headers onto the relayed message. The MIME structural,
|
||||
* address and subject headers are excluded (see {@link #SUPPRESSED_RELAY_HEADERS}), as are the
|
||||
* {@code X-SES-*} control headers: AWS consumes those rather than forwarding them.
|
||||
*/
|
||||
private static void copyRawHeaders(Message message, MailMessage mail) {
|
||||
Header header = message.getHeader();
|
||||
if (header == null) {
|
||||
return;
|
||||
}
|
||||
for (Field field : header.getFields()) {
|
||||
String name = field.getName();
|
||||
if (name == null || name.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String lower = name.toLowerCase(Locale.ROOT);
|
||||
if (SUPPRESSED_RELAY_HEADERS.contains(lower) || lower.startsWith(X_SES_PREFIX)) {
|
||||
continue;
|
||||
}
|
||||
String value = field.getBody();
|
||||
mail.addHeader(name, value == null ? "" : value.trim());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,25 +568,35 @@ public class SmtpRelay {
|
||||
if (textBody.getMimeCharset() != null) {
|
||||
try {
|
||||
charset = Charset.forName(textBody.getMimeCharset());
|
||||
} catch (Exception ignored) {}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("SMTP raw relay: unknown charset \"{0}\", reading part as UTF-8",
|
||||
textBody.getMimeCharset());
|
||||
}
|
||||
}
|
||||
try (var is = textBody.getInputStream()) {
|
||||
return new String(is.readAllBytes(), charset);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "SMTP raw relay: could not read a text part, relaying it as empty");
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Raw header parsing ────────────────────────────
|
||||
|
||||
/**
|
||||
* Structured headers extracted from a raw RFC 5322 MIME message: the From
|
||||
* address, subject, and separate To / Cc / Bcc address lists. Empty fields
|
||||
* Structured headers extracted from a raw RFC 5322 MIME message: the From address, subject,
|
||||
* separate To / Cc / Bcc address lists, the {@code Return-Path} envelope sender, and the
|
||||
* {@code X-SES-CONFIGURATION-SET} / {@code X-SES-MESSAGE-TAGS} control headers. Empty fields
|
||||
* when the corresponding header is missing.
|
||||
*/
|
||||
public record RawMessageHeaders(String from, String subject,
|
||||
List<String> to, List<String> cc, List<String> bcc) {
|
||||
List<String> to, List<String> cc, List<String> bcc,
|
||||
String returnPath, String configurationSet,
|
||||
List<MessageTag> messageTags) {
|
||||
public static RawMessageHeaders empty() {
|
||||
return new RawMessageHeaders("", "", List.of(), List.of(), List.of());
|
||||
return new RawMessageHeaders("", "", List.of(), List.of(), List.of(),
|
||||
"", "", List.of());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,12 +622,42 @@ public class SmtpRelay {
|
||||
? toMailboxAddresses(message.getCc().flatten()) : List.of();
|
||||
List<String> bcc = message.getBcc() != null
|
||||
? toMailboxAddresses(message.getBcc().flatten()) : List.of();
|
||||
return new RawMessageHeaders(from.isEmpty() ? "" : from.get(0), subject, to, cc, bcc);
|
||||
String returnPath = extractAngleAddress(headerValue(message, HEADER_RETURN_PATH));
|
||||
String configurationSet = headerValue(message, HEADER_CONFIGURATION_SET);
|
||||
List<MessageTag> messageTags = parseMessageTagsHeader(
|
||||
headerValue(message, HEADER_MESSAGE_TAGS));
|
||||
return new RawMessageHeaders(from.isEmpty() ? "" : from.get(0), subject, to, cc, bcc,
|
||||
returnPath == null ? "" : returnPath,
|
||||
configurationSet == null ? "" : configurationSet,
|
||||
messageTags);
|
||||
} catch (Exception e) {
|
||||
return RawMessageHeaders.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an {@code X-SES-MESSAGE-TAGS} header body: a comma-separated list of
|
||||
* {@code name=value} pairs. Entries without a name are skipped.
|
||||
*/
|
||||
static List<MessageTag> parseMessageTagsHeader(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
List<MessageTag> tags = new ArrayList<>();
|
||||
for (String pair : value.split(",")) {
|
||||
int separator = pair.indexOf('=');
|
||||
if (separator < 0) {
|
||||
continue;
|
||||
}
|
||||
String name = pair.substring(0, separator).trim();
|
||||
if (name.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
tags.add(new MessageTag(name, pair.substring(separator + 1).trim()));
|
||||
}
|
||||
return List.copyOf(tags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the flat list of recipients (To + Cc + Bcc) parsed from a raw RFC 5322
|
||||
* MIME message. Convenience wrapper around {@link #parseRawHeaders}.
|
||||
@@ -344,6 +671,57 @@ public class SmtpRelay {
|
||||
return all;
|
||||
}
|
||||
|
||||
private static String headerValue(Entity entity, String name) {
|
||||
Header header = entity.getHeader();
|
||||
if (header == null) {
|
||||
return null;
|
||||
}
|
||||
Field field = header.getField(name);
|
||||
if (field == null || field.getBody() == null) {
|
||||
return null;
|
||||
}
|
||||
String value = field.getBody().trim();
|
||||
return value.isEmpty() ? null : value;
|
||||
}
|
||||
|
||||
/** Unwraps the {@code <addr@example.com>} form used by Return-Path and friends. */
|
||||
static String extractAngleAddress(String value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
if (trimmed.startsWith("<") && trimmed.endsWith(">") && trimmed.length() > 2) {
|
||||
return trimmed.substring(1, trimmed.length() - 1).trim();
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
private static String firstNonBlank(String... values) {
|
||||
for (String value : values) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a mailbox for a relayed header, keeping any display name. Distinct from
|
||||
* {@link #toMailboxAddresses}, which yields the bare addresses that the envelope, the
|
||||
* suppression checks and the published events work with.
|
||||
*/
|
||||
private static String formatMailbox(Mailbox mailbox) {
|
||||
return AddressFormatter.DEFAULT.encode(mailbox);
|
||||
}
|
||||
|
||||
private static List<String> formatMailboxes(MailboxList list) {
|
||||
List<String> addresses = new ArrayList<>();
|
||||
for (Mailbox mailbox : list) {
|
||||
addresses.add(formatMailbox(mailbox));
|
||||
}
|
||||
return addresses;
|
||||
}
|
||||
|
||||
private static List<String> toMailboxAddresses(MailboxList list) {
|
||||
List<String> addresses = new ArrayList<>();
|
||||
for (Mailbox mailbox : list) {
|
||||
@@ -352,11 +730,42 @@ public class SmtpRelay {
|
||||
return addresses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes the {@code RawMessage.Data} blob, which SDK callers send base64-encoded but which
|
||||
* Floci also accepts as plain RFC 5322 text.
|
||||
*
|
||||
* <p>The alphabet is checked before decoding rather than relying on the decoder to reject
|
||||
* plain text: {@link Base64#getMimeDecoder()} skips characters outside the base64 alphabet, so
|
||||
* a plain-text message decodes into garbage whenever the remaining alphabet characters happen
|
||||
* to form a valid length. A real RFC 5322 message always carries a header separator, which is
|
||||
* not in the alphabet, so the check separates the two cases reliably.
|
||||
*/
|
||||
static byte[] tryBase64Decode(String data) {
|
||||
try {
|
||||
return Base64.getMimeDecoder().decode(data);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return data.getBytes(StandardCharsets.UTF_8);
|
||||
if (looksBase64Encoded(data)) {
|
||||
try {
|
||||
return Base64.getMimeDecoder().decode(data);
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOG.debugv("SES raw message looked base64-encoded but did not decode, "
|
||||
+ "treating it as plain text");
|
||||
}
|
||||
}
|
||||
return data.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static boolean looksBase64Encoded(String data) {
|
||||
boolean sawPayload = false;
|
||||
for (int i = 0; i < data.length(); i++) {
|
||||
char c = data.charAt(i);
|
||||
if (c == '\r' || c == '\n' || c == ' ' || c == '\t' || c == '=') {
|
||||
continue;
|
||||
}
|
||||
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
|
||||
|| c == '+' || c == '/') {
|
||||
sawPayload = true;
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return sawPayload;
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,9 @@ public class SentEmail {
|
||||
@JsonProperty("Source")
|
||||
private String source;
|
||||
|
||||
@JsonProperty("ReturnPath")
|
||||
private String returnPath;
|
||||
|
||||
@JsonProperty("Destination")
|
||||
private List<String> toAddresses;
|
||||
|
||||
@@ -92,6 +95,9 @@ public class SentEmail {
|
||||
public String getSource() { return source; }
|
||||
public void setSource(String source) { this.source = source; }
|
||||
|
||||
public String getReturnPath() { return returnPath; }
|
||||
public void setReturnPath(String returnPath) { this.returnPath = returnPath; }
|
||||
|
||||
public List<String> getToAddresses() { return toAddresses; }
|
||||
public void setToAddresses(List<String> toAddresses) { this.toAddresses = toAddresses; }
|
||||
|
||||
|
||||
Reference in new issue
Block a user