From 3671053d30b7e29f0caab1d64c5915c830a7ad96 Mon Sep 17 00:00:00 2001 From: op-techy Date: Fri, 4 Dec 2026 01:35:17 +0100 Subject: [PATCH] fix: honour opt-outs during sends, add one-click unsubscribe, escape merge tags - The send worker checks each email again before sending it: if the recipient unsubscribed, bounced or complained after the campaign was queued, the email is marked 'skipped' (new status, V2 migration) and counted in campaign_jobs.skipped_count instead of being sent. - Campaign emails carry List-Unsubscribe and List-Unsubscribe-Post (RFC 8058 one-click, required by Gmail and Yahoo for bulk senders). EmailSender takes extra headers; SES moves to SendRawEmail for them. - GET /track/unsubscribe/{token} now only shows a confirmation page, so link scanners can't unsubscribe people; POST does the unsubscribe. - New SuppressionService: every opt-out (link, API, bounce, complaint) sets the recipient's status and adds the address to the suppression list. Unsubscribing via the email link previously skipped the list. RecipientService normalises addresses, so a mixed-case re-add can't bypass an opt-out, and complained recipients can't be re-added. - Merge-tag values are HTML-escaped so imported data can't inject markup or links into emails. --- README.md | 22 ++-- .../controller/TrackingController.java | 66 ++++++++---- .../dto/response/JobStatusResponse.java | 2 + .../mailengine/entity/CampaignJob.java | 5 + .../mailengine/entity/enums/QueueStatus.java | 2 +- .../repository/CampaignJobRepository.java | 12 ++- .../repository/SuppressionListRepository.java | 11 ++ .../service/CampaignSendingService.java | 39 +++---- .../service/CompositeEmailSender.java | 9 +- .../mailengine/service/EmailSender.java | 15 ++- .../mailengine/service/MockEmailSender.java | 4 +- .../mailengine/service/RecipientService.java | 30 +++--- .../mailengine/service/ResendEmailSender.java | 4 +- .../mailengine/service/SesEmailSender.java | 52 ++++++--- .../mailengine/service/SesEventService.java | 23 +--- .../mailengine/service/SmtpEmailSender.java | 7 +- .../service/SuppressionService.java | 53 +++++++++ .../mailengine/service/TrackingService.java | 15 ++- .../mailengine/service/TrackingUrls.java | 28 +++++ .../mailengine/util/EmailAddresses.java | 15 +++ .../mailengine/worker/EmailQueueStore.java | 32 +++++- .../mailengine/worker/EmailSenderWorker.java | 32 ++++-- .../db/migration/V2__queue_skipped.sql | 7 ++ .../CampaignPipelineIntegrationTest.java | 81 ++++++++++++-- .../mailengine/service/EmailHeadersTest.java | 65 +++++++++++ .../service/SesEventServiceTest.java | 40 +++---- .../service/SuppressionServiceTest.java | 102 ++++++++++++++++++ .../worker/EmailSenderWorkerTest.java | 72 ++++++++++--- 28 files changed, 668 insertions(+), 177 deletions(-) create mode 100644 src/main/java/com/mailengine/mailengine/service/SuppressionService.java create mode 100644 src/main/java/com/mailengine/mailengine/service/TrackingUrls.java create mode 100644 src/main/java/com/mailengine/mailengine/util/EmailAddresses.java create mode 100644 src/main/resources/db/migration/V2__queue_skipped.sql create mode 100644 src/test/java/com/mailengine/mailengine/service/EmailHeadersTest.java create mode 100644 src/test/java/com/mailengine/mailengine/service/SuppressionServiceTest.java diff --git a/README.md b/README.md index ec52172..b714fb0 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,8 @@ Inbound webhooks: Public tracking (no auth): Email client ──► GET /track/open/{token} (1×1 PNG pixel) ──► GET /track/click/{token} (302 redirect) - ──► GET /track/unsubscribe/{token} (HTML page) + ──► GET /track/unsubscribe/{token} (confirmation page) + ──► POST /track/unsubscribe/{token} (unsubscribe; also one-click) ``` --- @@ -321,6 +322,7 @@ Schema is managed entirely by **Flyway**. Never edit the database by hand — ad ``` src/main/resources/db/migration/ V1__initial_schema.sql ← the whole schema, plus the seeded admin account + V2__queue_skipped.sql ← 'skipped' queue status and campaign_jobs.skipped_count ``` The original V1–V26 history was squashed into `V1` (no database had to be kept). Every change from now on is a new file. @@ -346,7 +348,7 @@ Flyway applies it automatically on the next startup. **Never modify an already-a | `recipients` | Contact records | | `recipient_lists` | Named groups of recipients | | `suppression_list` | Emails that must never be sent to again (bounces, complaints, unsubscribes) | -| `campaign_jobs` | Tracks the progress of an in-flight send (sentCount, failedCount, status) | +| `campaign_jobs` | Tracks the progress of an in-flight send (sentCount, failedCount, skippedCount, status) | | `engagement_scores` | Per-recipient RFM engagement score, refreshed nightly | | `file_uploads` | Tracks async CSV/XLSX/XLS import jobs; deleted with their list | | `pending_upload_files` | The file of an upload waiting for a column mapping (deleted once imported, or after a day) | @@ -517,7 +519,7 @@ Authorization: Bearer | POST | `/{id}/schedule` | Schedule for a future time | | POST | `/{id}/send` | Start the send pipeline immediately | | POST | `/{id}/test` | Send a preview to a list of test email addresses (`{"testEmails": [...]}`; 400 if empty or invalid) | -| GET | `/{id}/job-status` | Poll send progress: progress %, ETA, sent/failed counts | +| GET | `/{id}/job-status` | Poll send progress: progress %, ETA, sent/failed/skipped counts | | POST | `/{id}/pause` | Pause an in-progress send | | POST | `/{id}/resume` | Resume a paused send | @@ -578,7 +580,8 @@ Authorization: Bearer |---|---|---| | GET | `/open/{pixelToken}` | Called by email clients loading the 1×1 pixel | | GET | `/click/{clickToken}` | Logs click, redirects to original URL (404 unless that link is in that email) | -| GET | `/unsubscribe/{unsubToken}` | Marks recipient unsubscribed, returns HTML confirmation | +| GET | `/unsubscribe/{unsubToken}` | Confirmation page with an Unsubscribe button; changes nothing (link scanners open every link) | +| POST | `/unsubscribe/{unsubToken}` | Unsubscribes and suppresses the address. The page's button, and mail clients' one-click unsubscribe (RFC 8058) | ### Webhooks — `/webhooks` (public, no auth) @@ -607,6 +610,7 @@ When you call `POST /api/campaigns/{id}/send`, this is what happens: 3. Personalise HTML (for each recipient) └─ Replace merge tags: {{first_name}} {{last_name}} {{email}} {{company}} + (values are HTML-escaped: imported data can't add markup or links) └─ Rewrite links: href="https://..." → href="/track/click/{clickToken}?t={base64url(originalUrl)}" (skips mailto:, #anchors, already-tracked links) @@ -634,8 +638,12 @@ Every 3 seconds (at most app.sending.rate-per-second emails per second, default FOR UPDATE SKIP LOCKED ← safe for multiple concurrent workers For each row: - If campaign is PAUSED → skip - Send via CompositeEmailSender (Resend → SES → SMTP) + If campaign is PAUSED → hand back to pending + If the recipient is no longer active or the address is suppressed + (unsubscribed, bounced or complained since queueing) → status = SKIPPED, not sent + Send via CompositeEmailSender (Resend → SES → SMTP), with the headers + List-Unsubscribe: <{APP_BASE_URL}/track/unsubscribe/{unsubToken}> + List-Unsubscribe-Post: List-Unsubscribe=One-Click Success → status = SENT, store SES messageId (for webhook correlation) Failure → increment attempts @@ -683,7 +691,7 @@ Country and city come from a MaxMind database file read locally: no network call ``` {APP_BASE_URL}/track/unsubscribe/{unsubToken} ``` -On click: `recipient.status = UNSUBSCRIBED` → add to `suppression_list` → return HTML confirmation page. +Opening the link shows a confirmation page with an Unsubscribe button; it changes nothing, because link scanners (Outlook Safe Links, Mimecast) open every link in an email. The button POSTs to the same URL, as does the mail client's own Unsubscribe button (one-click, from the `List-Unsubscribe` headers that Gmail and Yahoo require of bulk senders). On POST: `recipient.status = UNSUBSCRIBED` (if active) → add to `suppression_list` → return the confirmation page. The worker checks again before every email, so an unsubscribe takes effect even during a send that is already running. > `APP_BASE_URL` must be publicly reachable by real email clients. Set it to your ngrok URL during local development. diff --git a/src/main/java/com/mailengine/mailengine/controller/TrackingController.java b/src/main/java/com/mailengine/mailengine/controller/TrackingController.java index e7e5fb7..8240694 100644 --- a/src/main/java/com/mailengine/mailengine/controller/TrackingController.java +++ b/src/main/java/com/mailengine/mailengine/controller/TrackingController.java @@ -7,6 +7,9 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; +import org.springframework.web.util.HtmlUtils; + +import java.util.regex.Pattern; /** * Handles all public tracking endpoints embedded in outgoing emails. @@ -20,7 +23,8 @@ *
    *
  • {@code GET /track/open/{pixelToken}} — logs open event, returns 1×1 PNG
  • *
  • {@code GET /track/click/{clickToken}} — logs click event, 302-redirects to original URL
  • - *
  • {@code GET /track/unsubscribe/{unsubToken}} — marks recipient unsubscribed, shows confirmation HTML
  • + *
  • {@code GET /track/unsubscribe/{unsubToken}} — confirmation page; {@code POST} (its button, or one-click + * from the mail provider) unsubscribes
  • *
* *

Keep these endpoints as lean as possible. Email clients time out quickly @@ -103,38 +107,52 @@ public ResponseEntity trackClick( } /** - * Unsubscribe endpoint — marks recipient as unsubscribed and shows a confirmation page. + * Unsubscribe link in the email footer: shows a confirmation page and changes nothing. * - *

Every outgoing email includes an unsubscribe link: - *

-     *   <a href="https://api.yourapp.com/track/unsubscribe/{unsubToken}">Unsubscribe</a>
-     * 
- * When clicked, the recipient's status is set to UNSUBSCRIBED in the database - * and a simple server-rendered HTML confirmation page is returned. - * No React or frontend framework is needed for this page. + *

A GET must not unsubscribe: link scanners (Outlook Safe Links, Mimecast and others) open every link + * in an email, which would unsubscribe people who never clicked. The page's button POSTs to the same URL. * *

GET /track/unsubscribe/{unsubToken} - * - * @param unsubToken the unique token identifying this recipient's queued email - * @return a plain HTML confirmation page */ @GetMapping(value = "/unsubscribe/{unsubToken}", produces = MediaType.TEXT_HTML_VALUE) - public ResponseEntity trackUnsubscribe(@PathVariable String unsubToken) { - String companyName = trackingService.handleUnsubscribe(unsubToken); + public ResponseEntity confirmUnsubscribe(@PathVariable String unsubToken) { + // The token is a UUID; anything else is dropped so it can't reach the HTML + String action = UNSUB_TOKEN.matcher(unsubToken).matches() ? unsubToken : ""; + return ResponseEntity.ok(page("Unsubscribe?", + "

Click below to stop receiving these emails.

" + + "
" + + "
")); + } - // Fall back to a generic phrase if the company name cannot be resolved + /** + * Unsubscribes the recipient. Called by the confirmation page's button, and by mail providers' one-click + * unsubscribe (RFC 8058: the email's {@code List-Unsubscribe-Post} header; the body, + * {@code List-Unsubscribe=One-Click}, is not needed). + * + *

POST /track/unsubscribe/{unsubToken} + */ + @PostMapping(value = "/unsubscribe/{unsubToken}", produces = MediaType.TEXT_HTML_VALUE) + public ResponseEntity unsubscribe(@PathVariable String unsubToken) { + String companyName = trackingService.handleUnsubscribe(unsubToken); if (companyName == null) { companyName = "this mailing list"; } + return ResponseEntity.ok(page("You have been unsubscribed", + "

You will no longer receive emails from " + HtmlUtils.htmlEscape(companyName) + + ".

")); + } - // Minimal, responsive confirmation HTML — no external dependencies - String html = """ + private static final Pattern UNSUB_TOKEN = Pattern.compile("[0-9a-fA-F-]{36}"); + + /** Minimal, responsive page with no external dependencies. */ + private static String page(String heading, String bodyHtml) { + return """ - Unsubscribed + %s
-

You have been unsubscribed

-

You will no longer receive emails from %s.

+

%s

+ %s
- """.formatted(companyName); - - return ResponseEntity.ok(html); + """.formatted(heading, heading, bodyHtml); } } diff --git a/src/main/java/com/mailengine/mailengine/dto/response/JobStatusResponse.java b/src/main/java/com/mailengine/mailengine/dto/response/JobStatusResponse.java index cb9cfc9..6b979a6 100644 --- a/src/main/java/com/mailengine/mailengine/dto/response/JobStatusResponse.java +++ b/src/main/java/com/mailengine/mailengine/dto/response/JobStatusResponse.java @@ -18,6 +18,8 @@ public class JobStatusResponse { private Integer totalEmails; private Integer sentCount; private Integer failedCount; + /** Not sent because the recipient unsubscribed, bounced or complained after the campaign was queued. */ + private Integer skippedCount; private Integer progress; private Instant startedAt; private Instant completedAt; diff --git a/src/main/java/com/mailengine/mailengine/entity/CampaignJob.java b/src/main/java/com/mailengine/mailengine/entity/CampaignJob.java index 76ce4bc..8d4ce09 100644 --- a/src/main/java/com/mailengine/mailengine/entity/CampaignJob.java +++ b/src/main/java/com/mailengine/mailengine/entity/CampaignJob.java @@ -59,6 +59,11 @@ public class CampaignJob { @Column(name = "failed_count") private Integer failedCount; + // Incremented when the worker drops an email because its recipient opted out after it was queued + @ColumnDefault("0") + @Column(name = "skipped_count") + private Integer skippedCount; + @Column(name = "started_at") private Instant startedAt; diff --git a/src/main/java/com/mailengine/mailengine/entity/enums/QueueStatus.java b/src/main/java/com/mailengine/mailengine/entity/enums/QueueStatus.java index 6c9e453..3114ced 100644 --- a/src/main/java/com/mailengine/mailengine/entity/enums/QueueStatus.java +++ b/src/main/java/com/mailengine/mailengine/entity/enums/QueueStatus.java @@ -1,5 +1,5 @@ package com.mailengine.mailengine.entity.enums; public enum QueueStatus { - pending, sending, sent, failed + pending, sending, sent, failed, skipped } diff --git a/src/main/java/com/mailengine/mailengine/repository/CampaignJobRepository.java b/src/main/java/com/mailengine/mailengine/repository/CampaignJobRepository.java index ef034f3..ab26344 100644 --- a/src/main/java/com/mailengine/mailengine/repository/CampaignJobRepository.java +++ b/src/main/java/com/mailengine/mailengine/repository/CampaignJobRepository.java @@ -39,4 +39,14 @@ public interface CampaignJobRepository extends JpaRepository WHERE j.campaign.id = :campaignId """) void incrementFailedCount(@Param("campaignId") Long campaignId, @Param("count") int count); -} \ No newline at end of file + + // Atomically increments skippedCount: emails not sent because the recipient opted out after queueing + @Transactional + @Modifying + @Query(""" + UPDATE CampaignJob j + SET j.skippedCount = COALESCE(j.skippedCount, 0) + :count + WHERE j.campaign.id = :campaignId + """) + void incrementSkippedCount(@Param("campaignId") Long campaignId, @Param("count") int count); +} diff --git a/src/main/java/com/mailengine/mailengine/repository/SuppressionListRepository.java b/src/main/java/com/mailengine/mailengine/repository/SuppressionListRepository.java index 9616b8b..7567b7b 100644 --- a/src/main/java/com/mailengine/mailengine/repository/SuppressionListRepository.java +++ b/src/main/java/com/mailengine/mailengine/repository/SuppressionListRepository.java @@ -2,10 +2,21 @@ import com.mailengine.mailengine.entity.SuppressionList; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import java.util.Optional; public interface SuppressionListRepository extends JpaRepository { boolean existsByEmail(String email); Optional findByEmail(String email); + + /** Inserts the (already normalised) address unless it is there; never fails on a concurrent insert. */ + @Modifying + @Query(value = """ + INSERT INTO suppression_list (email, reason, created_at) VALUES (:email, :reason, NOW()) + ON CONFLICT (email) DO NOTHING + """, nativeQuery = true) + int insertIfAbsent(@Param("email") String email, @Param("reason") String reason); } \ No newline at end of file diff --git a/src/main/java/com/mailengine/mailengine/service/CampaignSendingService.java b/src/main/java/com/mailengine/mailengine/service/CampaignSendingService.java index 70fcf17..32aa7e8 100644 --- a/src/main/java/com/mailengine/mailengine/service/CampaignSendingService.java +++ b/src/main/java/com/mailengine/mailengine/service/CampaignSendingService.java @@ -8,9 +8,9 @@ import com.mailengine.mailengine.repository.*; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.util.HtmlUtils; import java.nio.charset.StandardCharsets; import java.time.Instant; @@ -26,12 +26,10 @@ public class CampaignSendingService { private final CampaignJobRepository campaignJobRepository; private final CampaignRecipientListRepository campaignRecipientListRepository; private final RecipientListMemberRepository recipientListMemberRepository; - private final SuppressionListRepository suppressionListRepository; private final EmailQueueRepository emailQueueRepository; private final EmailSender emailSender; - - @Value("${app.base-url}") - private String baseUrl; + private final SuppressionService suppressionService; + private final TrackingUrls trackingUrls; // ───────────────────────────────────────────────────────────────────────────── // SEND PIPELINE @@ -100,6 +98,7 @@ public void sendCampaign(Long campaignId) { job.setQueuedCount(recipients.size()); job.setSentCount(0); job.setFailedCount(0); + job.setSkippedCount(0); job.setStartedAt(Instant.now()); campaignJobRepository.save(job); @@ -152,7 +151,8 @@ public JobStatusResponse getJobStatus(Long campaignId) { .orElseThrow(() -> new ResourceNotFoundException( "No job found for campaign: " + campaignId)); - int processed = job.getSentCount() + job.getFailedCount(); + int skipped = job.getSkippedCount() != null ? job.getSkippedCount() : 0; + int processed = job.getSentCount() + job.getFailedCount() + skipped; int total = job.getTotalEmails() != null ? job.getTotalEmails() : 0; int progress = total > 0 ? (int) Math.round((processed * 100.0) / total) : 0; @@ -161,6 +161,7 @@ public JobStatusResponse getJobStatus(Long campaignId) { .totalEmails(total) .sentCount(job.getSentCount()) .failedCount(job.getFailedCount()) + .skippedCount(skipped) .progress(progress) .startedAt(job.getStartedAt()) .completedAt(job.getCompletedAt()) @@ -226,7 +227,7 @@ private List collectEligibleRecipients(Campaign campaign) { if (seenEmails.contains(email)) continue; if (r.getStatus() != RecipientStatus.active) continue; - if (suppressionListRepository.existsByEmail(email)) continue; + if (suppressionService.isSuppressed(email)) continue; seenEmails.add(email); eligible.add(r); @@ -245,12 +246,17 @@ private String personaliseHtml(String html, Recipient recipient, return result; } + /** Recipient data comes from imports, so it is HTML-escaped: it must never add markup or links to the email. */ private String replaceMergeTags(String html, Recipient r) { return html - .replace("{{first_name}}", nullSafe(r.getFirstName())) - .replace("{{last_name}}", nullSafe(r.getLastName())) - .replace("{{email}}", nullSafe(r.getEmail())) - .replace("{{company}}", nullSafe(r.getCompany())); + .replace("{{first_name}}", escaped(r.getFirstName())) + .replace("{{last_name}}", escaped(r.getLastName())) + .replace("{{email}}", escaped(r.getEmail())) + .replace("{{company}}", escaped(r.getCompany())); + } + + private static String escaped(String value) { + return value == null ? "" : HtmlUtils.htmlEscape(value); } private String rewriteLinksForClickTracking(String html, String clickToken) { @@ -271,7 +277,7 @@ private String rewriteLinksForClickTracking(String html, String clickToken) { String encoded = Base64.getUrlEncoder().withoutPadding() .encodeToString(originalUrl.getBytes(StandardCharsets.UTF_8)); - String trackedUrl = baseUrl + "/track/click/" + clickToken + "?t=" + encoded; + String trackedUrl = trackingUrls.clickUrl(clickToken, encoded); matcher.appendReplacement(result, Matcher.quoteReplacement("href=\"" + trackedUrl + "\"")); } @@ -280,7 +286,7 @@ private String rewriteLinksForClickTracking(String html, String clickToken) { } private String injectUnsubscribeUrl(String html, String unsubToken) { - String unsubUrl = baseUrl + "/track/unsubscribe/" + unsubToken; + String unsubUrl = trackingUrls.unsubscribeUrl(unsubToken); if (html.contains("{{unsubscribe_url}}")) { return html.replace("{{unsubscribe_url}}", unsubUrl); @@ -292,8 +298,7 @@ private String injectUnsubscribeUrl(String html, String unsubToken) { } private String injectTrackingPixel(String html, String pixelToken) { - String pixelUrl = baseUrl + "/track/open/" + pixelToken - + "?cb=" + System.currentTimeMillis(); + String pixelUrl = trackingUrls.pixelUrl(pixelToken); String pixelTag = ""; return injectBeforeClosingBody(html, pixelTag); @@ -307,10 +312,6 @@ private String injectBeforeClosingBody(String html, String content) { return html + content; } - private String nullSafe(String value) { - return value != null ? value : ""; - } - private Long estimateEta(CampaignJob job, int processed, int total) { if (job.getStartedAt() == null || processed == 0 || total == 0) return null; if (job.getStatus() != JobStatus.processing) return null; diff --git a/src/main/java/com/mailengine/mailengine/service/CompositeEmailSender.java b/src/main/java/com/mailengine/mailengine/service/CompositeEmailSender.java index 12ebc40..86c6b2b 100644 --- a/src/main/java/com/mailengine/mailengine/service/CompositeEmailSender.java +++ b/src/main/java/com/mailengine/mailengine/service/CompositeEmailSender.java @@ -1,5 +1,6 @@ package com.mailengine.mailengine.service; +import java.util.Map; import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -28,17 +29,17 @@ public void init() { @Override public String send(String toEmail, String fromName, String fromEmail, - String subject, String htmlContent) { + String subject, String htmlContent, Map headers) { // 1. Try Resend API first (most reliable on Railway) - String messageId = resendEmailSender.send(toEmail, fromName, fromEmail, subject, htmlContent); + String messageId = resendEmailSender.send(toEmail, fromName, fromEmail, subject, htmlContent, headers); if (messageId != null) { return messageId; } // 2. Fallback to SES if healthy if (sesHealthy) { - messageId = sesEmailSender.send(toEmail, fromName, fromEmail, subject, htmlContent); + messageId = sesEmailSender.send(toEmail, fromName, fromEmail, subject, htmlContent, headers); if (messageId != null) { return messageId; } @@ -46,6 +47,6 @@ public String send(String toEmail, String fromName, String fromEmail, } // 3. Final fallback to SMTP - return smtpEmailSender.send(toEmail, fromName, fromEmail, subject, htmlContent); + return smtpEmailSender.send(toEmail, fromName, fromEmail, subject, htmlContent, headers); } } \ No newline at end of file diff --git a/src/main/java/com/mailengine/mailengine/service/EmailSender.java b/src/main/java/com/mailengine/mailengine/service/EmailSender.java index 4385183..2f122fe 100644 --- a/src/main/java/com/mailengine/mailengine/service/EmailSender.java +++ b/src/main/java/com/mailengine/mailengine/service/EmailSender.java @@ -1,5 +1,7 @@ package com.mailengine.mailengine.service; +import java.util.Map; + /** * Unified interface for sending a single email. * @@ -30,6 +32,17 @@ public interface EmailSender { * @param htmlContent the fully personalised HTML body — merge tags already replaced * @return a unique message ID if the email was accepted; {@code null} if it failed */ + default String send(String toEmail, String fromName, String fromEmail, + String subject, String htmlContent) { + return send(toEmail, fromName, fromEmail, subject, htmlContent, Map.of()); + } + + /** + * Sends a single HTML email with extra headers, such as {@code List-Unsubscribe} on campaign emails. + * + * @param headers extra header names and values; may be empty, never {@code null} + * @return a unique message ID if the email was accepted; {@code null} if it failed + */ String send(String toEmail, String fromName, String fromEmail, - String subject, String htmlContent); + String subject, String htmlContent, Map headers); } diff --git a/src/main/java/com/mailengine/mailengine/service/MockEmailSender.java b/src/main/java/com/mailengine/mailengine/service/MockEmailSender.java index 9c5823c..59218fe 100644 --- a/src/main/java/com/mailengine/mailengine/service/MockEmailSender.java +++ b/src/main/java/com/mailengine/mailengine/service/MockEmailSender.java @@ -1,5 +1,6 @@ package com.mailengine.mailengine.service; +import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Primary; @@ -42,11 +43,12 @@ public class MockEmailSender implements EmailSender { */ @Override public String send(String toEmail, String fromName, String fromEmail, - String subject, String htmlContent) { + String subject, String htmlContent, Map headers) { log.info("========== MOCK EMAIL SENT =========="); log.info("To: {}", toEmail); log.info("From: {} <{}>", fromName, fromEmail); log.info("Subject: {}", subject); + headers.forEach((name, value) -> log.info("{}: {}", name, value)); log.info("HTML Length: {} characters", htmlContent.length()); // The readable text and the links, so a developer can use what the email carries (an invite's // temporary password, a reset link) without a mail server. Development only: never run with diff --git a/src/main/java/com/mailengine/mailengine/service/RecipientService.java b/src/main/java/com/mailengine/mailengine/service/RecipientService.java index a918192..97dc216 100644 --- a/src/main/java/com/mailengine/mailengine/service/RecipientService.java +++ b/src/main/java/com/mailengine/mailengine/service/RecipientService.java @@ -7,6 +7,7 @@ import com.mailengine.mailengine.exception.BadRequestException; import com.mailengine.mailengine.exception.ResourceNotFoundException; import com.mailengine.mailengine.repository.*; +import com.mailengine.mailengine.util.EmailAddresses; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -22,7 +23,7 @@ public class RecipientService { private final RecipientRepository recipientRepository; private final RecipientListRepository recipientListRepository; private final RecipientListMemberRepository recipientListMemberRepository; - private final SuppressionListRepository suppressionListRepository; + private final SuppressionService suppressionService; @Transactional(readOnly = true) public Page getRecipients(Long listId, String search, Pageable pageable) { @@ -35,21 +36,22 @@ public Page getRecipients(Long listId, String search, Pageabl } public RecipientResponse addRecipient(Long listId, CreateRecipientRequest request) { - if (suppressionListRepository.existsByEmail(request.getEmail())) { + // Normalised like imports, so "Foo@X.com" can't slip past an opt-out recorded for "foo@x.com" + String email = EmailAddresses.normalize(request.getEmail()); + if (suppressionService.isSuppressed(email)) { throw new BadRequestException("This email address is suppressed and cannot be added"); } - Recipient recipient = recipientRepository.findByEmail(request.getEmail()) + Recipient recipient = recipientRepository.findByEmail(email) .orElseGet(() -> { Recipient r = new Recipient(); - r.setEmail(request.getEmail()); + r.setEmail(email); r.setStatus(RecipientStatus.active); return r; }); - if (recipient.getStatus() == RecipientStatus.unsubscribed || - recipient.getStatus() == RecipientStatus.bounced) { - throw new BadRequestException("Recipient has unsubscribed or bounced and cannot be added"); + if (recipient.getStatus() != RecipientStatus.active) { + throw new BadRequestException("Recipient has unsubscribed, bounced or complained and cannot be added"); } recipient.setFirstName(request.getFirstName()); @@ -67,17 +69,9 @@ public RecipientResponse addRecipient(Long listId, CreateRecipientRequest reques } public void unsubscribe(String email) { - recipientRepository.findByEmail(email).ifPresent(r -> { - r.setStatus(RecipientStatus.unsubscribed); - recipientRepository.save(r); - }); - - if (!suppressionListRepository.existsByEmail(email)) { - SuppressionList entry = new SuppressionList(); - entry.setEmail(email.toLowerCase()); - entry.setReason("unsubscribed"); - suppressionListRepository.save(entry); - } + String address = EmailAddresses.normalize(email); + Recipient recipient = recipientRepository.findByEmail(address).orElse(null); + suppressionService.optOut(recipient, address, RecipientStatus.unsubscribed, "unsubscribed"); } private RecipientList findOrThrow(Long listId) { diff --git a/src/main/java/com/mailengine/mailengine/service/ResendEmailSender.java b/src/main/java/com/mailengine/mailengine/service/ResendEmailSender.java index ae1b092..bb5cdb7 100644 --- a/src/main/java/com/mailengine/mailengine/service/ResendEmailSender.java +++ b/src/main/java/com/mailengine/mailengine/service/ResendEmailSender.java @@ -1,5 +1,6 @@ package com.mailengine.mailengine.service; +import java.util.Map; import com.resend.Resend; import com.resend.core.exception.ResendException; import com.resend.services.emails.model.CreateEmailOptions; @@ -32,7 +33,7 @@ public void init() { @Override public String send(String toEmail, String fromName, String fromEmail, - String subject, String htmlContent) { + String subject, String htmlContent, Map headers) { if (resend == null) return null; // not configured: the caller falls back to the next sender try { String from = String.format("%s <%s>", fromName, fromEmail); @@ -42,6 +43,7 @@ public String send(String toEmail, String fromName, String fromEmail, .to(toEmail) .subject(subject) .html(htmlContent) + .headers(headers) .build(); CreateEmailResponse response = resend.emails().send(options); diff --git a/src/main/java/com/mailengine/mailengine/service/SesEmailSender.java b/src/main/java/com/mailengine/mailengine/service/SesEmailSender.java index ac4e56d..c8d3190 100644 --- a/src/main/java/com/mailengine/mailengine/service/SesEmailSender.java +++ b/src/main/java/com/mailengine/mailengine/service/SesEmailSender.java @@ -4,9 +4,19 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.stereotype.Component; +import jakarta.mail.MessagingException; +import jakarta.mail.Session; +import jakarta.mail.internet.MimeMessage; +import org.springframework.mail.javamail.MimeMessageHelper; +import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.ses.SesClient; import software.amazon.awssdk.services.ses.model.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Map; +import java.util.Properties; + /** * Sends emails via AWS Simple Email Service (SES). * @@ -37,8 +47,8 @@ public class SesEmailSender implements EmailSender { /** * Sends a single HTML email via AWS SES. * - *

Constructs the {@code From} header as: {@code "Display Name "} - * which is how most email clients display the sender. + *

The {@code From} header is {@code "Display Name "}, which is how most email + * clients display the sender. * * @param toEmail recipient address * @param fromName display name (e.g. "MailEngine Team") @@ -49,25 +59,16 @@ public class SesEmailSender implements EmailSender { */ @Override public String send(String toEmail, String fromName, String fromEmail, - String subject, String htmlContent) { + String subject, String htmlContent, Map headers) { try { - // SES expects "Display Name " in the Source field - String fromHeader = fromName + " <" + fromEmail + ">"; - - SendEmailRequest request = SendEmailRequest.builder() - .destination(Destination.builder().toAddresses(toEmail).build()) - .message(Message.builder() - .subject(Content.builder() - .data(subject).charset("UTF-8").build()) - .body(Body.builder() - .html(Content.builder() - .data(htmlContent).charset("UTF-8").build()) - .build()) + // SendRawEmail, because SES's simple SendEmail can't carry extra headers (List-Unsubscribe) + SendRawEmailRequest request = SendRawEmailRequest.builder() + .rawMessage(RawMessage.builder() + .data(SdkBytes.fromByteArray(mime(toEmail, fromName, fromEmail, subject, htmlContent, headers))) .build()) - .source(fromHeader) .build(); - SendEmailResponse response = sesClient.sendEmail(request); + SendRawEmailResponse response = sesClient.sendRawEmail(request); log.debug("SES accepted email to {} — messageId: {}", toEmail, response.messageId()); // Return the SES message ID so the worker can store it for webhook matching return response.messageId(); @@ -87,6 +88,23 @@ public String send(String toEmail, String fromName, String fromEmail, } } + /** The complete MIME message: From "Display Name

", To, Subject, the HTML body and the extra headers. */ + static byte[] mime(String toEmail, String fromName, String fromEmail, String subject, String htmlContent, + Map headers) throws MessagingException, IOException { + MimeMessage message = new MimeMessage(Session.getInstance(new Properties())); + MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); + helper.setTo(toEmail); + helper.setFrom(fromEmail, fromName); + helper.setSubject(subject); + helper.setText(htmlContent, true); + for (Map.Entry header : headers.entrySet()) { + message.setHeader(header.getKey(), header.getValue()); + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + message.writeTo(out); + return out.toByteArray(); + } + /** * Checks whether SES is reachable and the credentials have the required permissions. * diff --git a/src/main/java/com/mailengine/mailengine/service/SesEventService.java b/src/main/java/com/mailengine/mailengine/service/SesEventService.java index 1f4929d..efe43a5 100644 --- a/src/main/java/com/mailengine/mailengine/service/SesEventService.java +++ b/src/main/java/com/mailengine/mailengine/service/SesEventService.java @@ -3,13 +3,12 @@ import com.fasterxml.jackson.databind.JsonNode; import com.mailengine.mailengine.entity.EmailQueue; import com.mailengine.mailengine.entity.Recipient; -import com.mailengine.mailengine.entity.SuppressionList; import com.mailengine.mailengine.entity.TrackingEvent; import com.mailengine.mailengine.entity.enums.RecipientStatus; import com.mailengine.mailengine.repository.EmailQueueRepository; import com.mailengine.mailengine.repository.RecipientRepository; -import com.mailengine.mailengine.repository.SuppressionListRepository; import com.mailengine.mailengine.repository.TrackingEventRepository; +import com.mailengine.mailengine.util.EmailAddresses; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -35,7 +34,7 @@ public class SesEventService { private final EmailQueueRepository emailQueueRepository; private final TrackingEventRepository trackingEventRepository; private final RecipientRepository recipientRepository; - private final SuppressionListRepository suppressionListRepository; + private final SuppressionService suppressionService; /** @param message the SES event: the parsed {@code Message} of an SNS notification */ @Transactional @@ -58,7 +57,7 @@ public void handle(JsonNode message) { boolean permanentBounce = type.equals("Bounce") && "Permanent".equals(event.path("bounceType").asText()); for (JsonNode node : event.path("recipients")) { // bounce/complaint list objects {"emailAddress": ...}; delivery lists plain strings - String address = normalize(node.isTextual() ? node.asText() : node.path("emailAddress").asText()); + String address = EmailAddresses.normalize(node.isTextual() ? node.asText() : node.path("emailAddress").asText()); Recipient recipient = address.isEmpty() ? null : recipientRepository.findByEmail(address) .orElse(sent.map(EmailQueue::getRecipient).orElse(null)); @@ -78,20 +77,6 @@ private void record(EmailQueue email, Recipient recipient, String eventType) { } private void stopMailing(String address, Recipient recipient, RecipientStatus status, String reason) { - if (recipient != null && recipient.getStatus() == RecipientStatus.active) { - recipient.setStatus(status); - recipientRepository.save(recipient); - } - if (!address.isEmpty() && !suppressionListRepository.existsByEmail(address)) { - SuppressionList entry = new SuppressionList(); - entry.setEmail(address); - entry.setReason(reason); - suppressionListRepository.save(entry); - } - log.info("Stopped mailing {} ({})", address, reason); - } - - private static String normalize(String email) { - return email == null ? "" : email.trim().toLowerCase(Locale.ROOT); + suppressionService.optOut(recipient, address, status, reason); } } diff --git a/src/main/java/com/mailengine/mailengine/service/SmtpEmailSender.java b/src/main/java/com/mailengine/mailengine/service/SmtpEmailSender.java index e30865d..5242ceb 100644 --- a/src/main/java/com/mailengine/mailengine/service/SmtpEmailSender.java +++ b/src/main/java/com/mailengine/mailengine/service/SmtpEmailSender.java @@ -1,5 +1,6 @@ package com.mailengine.mailengine.service; +import java.util.Map; import jakarta.mail.MessagingException; import jakarta.mail.internet.InternetAddress; import jakarta.mail.internet.MimeMessage; @@ -56,7 +57,7 @@ public class SmtpEmailSender implements EmailSender { */ @Override public String send(String toEmail, String fromName, String fromEmail, - String subject, String htmlContent) { + String subject, String htmlContent, Map headers) { // MailConfig always turns SMTP auth on, so without MAIL_USERNAME there is no usable SMTP account if (javaMailSender instanceof JavaMailSenderImpl impl && (impl.getUsername() == null || impl.getUsername().isBlank())) { @@ -83,6 +84,10 @@ public String send(String toEmail, String fromName, String fromEmail, // Set Reply-To so replies go to the brand email, not the SMTP account helper.setReplyTo(fromEmail); + for (Map.Entry header : headers.entrySet()) { + message.setHeader(header.getKey(), header.getValue()); + } + javaMailSender.send(message); // Generate a synthetic message ID (SMTP doesn't always return one) diff --git a/src/main/java/com/mailengine/mailengine/service/SuppressionService.java b/src/main/java/com/mailengine/mailengine/service/SuppressionService.java new file mode 100644 index 0000000..45239cd --- /dev/null +++ b/src/main/java/com/mailengine/mailengine/service/SuppressionService.java @@ -0,0 +1,53 @@ +package com.mailengine.mailengine.service; + +import com.mailengine.mailengine.entity.Recipient; +import com.mailengine.mailengine.entity.enums.RecipientStatus; +import com.mailengine.mailengine.repository.RecipientRepository; +import com.mailengine.mailengine.repository.SuppressionListRepository; +import com.mailengine.mailengine.util.EmailAddresses; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * The one place that decides an address must not be mailed again, and that answers whether it may be. + * + *

Unsubscribes (the email link, one-click, the API), permanent bounces and complaints all end here, so each + * of them both changes the recipient's status and puts the address on the suppression list. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class SuppressionService { + + private final SuppressionListRepository suppressionListRepository; + private final RecipientRepository recipientRepository; + + @Transactional(readOnly = true) + public boolean isSuppressed(String email) { + String address = EmailAddresses.normalize(email); + return !address.isEmpty() && suppressionListRepository.existsByEmail(address); + } + + /** Adds the address to the suppression list; does nothing if it is already there (even from a concurrent insert). */ + @Transactional + public void suppress(String email, String reason) { + String address = EmailAddresses.normalize(email); + if (!address.isEmpty()) suppressionListRepository.insertIfAbsent(address, reason); + } + + /** + * Stops all mail to an address: the recipient (if any, and only if still active, so a bounce is not turned + * into an unsubscribe) gets {@code status}, and the address joins the suppression list. + */ + @Transactional + public void optOut(Recipient recipient, String email, RecipientStatus status, String reason) { + if (recipient != null && recipient.getStatus() == RecipientStatus.active) { + recipient.setStatus(status); + recipientRepository.save(recipient); + } + suppress(email, reason); + log.info("Stopped mailing {} ({})", EmailAddresses.normalize(email), reason); + } +} diff --git a/src/main/java/com/mailengine/mailengine/service/TrackingService.java b/src/main/java/com/mailengine/mailengine/service/TrackingService.java index c455486..70dd844 100644 --- a/src/main/java/com/mailengine/mailengine/service/TrackingService.java +++ b/src/main/java/com/mailengine/mailengine/service/TrackingService.java @@ -5,7 +5,6 @@ import com.mailengine.mailengine.entity.TrackingEvent; import com.mailengine.mailengine.entity.enums.RecipientStatus; import com.mailengine.mailengine.repository.EmailQueueRepository; -import com.mailengine.mailengine.repository.RecipientRepository; import com.mailengine.mailengine.repository.TrackingEventRepository; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; @@ -46,7 +45,7 @@ public class TrackingService { private final EmailQueueRepository emailQueueRepository; private final TrackingEventRepository trackingEventRepository; - private final RecipientRepository recipientRepository; + private final SuppressionService suppressionService; private final GeoIpService geoIpService; private final UserAgentParserService userAgentParserService; @@ -209,14 +208,12 @@ public String handleUnsubscribe(String unsubToken) { return null; } + // Status and suppression list both, so the address can't come back through an import or a manual add Recipient recipient = queued.getRecipient(); - if (recipient != null) { - recipient.setStatus(RecipientStatus.unsubscribed); - recipientRepository.save(recipient); - log.info("Recipient {} unsubscribed from campaign {}", - recipient.getId(), - queued.getCampaign() != null ? queued.getCampaign().getId() : "?"); - } + suppressionService.optOut(recipient, queued.getToEmail(), RecipientStatus.unsubscribed, "unsubscribed"); + log.info("Recipient {} unsubscribed from campaign {}", + recipient != null ? recipient.getId() : "?", + queued.getCampaign() != null ? queued.getCampaign().getId() : "?"); // Log the unsubscribe event regardless of whether the recipient was found TrackingEvent event = new TrackingEvent(); diff --git a/src/main/java/com/mailengine/mailengine/service/TrackingUrls.java b/src/main/java/com/mailengine/mailengine/service/TrackingUrls.java new file mode 100644 index 0000000..551b0c6 --- /dev/null +++ b/src/main/java/com/mailengine/mailengine/service/TrackingUrls.java @@ -0,0 +1,28 @@ +package com.mailengine.mailengine.service; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** Builds the public tracking URLs (served by TrackingController) that go into every campaign email. */ +@Component +public class TrackingUrls { + + private final String baseUrl; + + public TrackingUrls(@Value("${app.base-url}") String baseUrl) { + this.baseUrl = baseUrl; + } + + public String unsubscribeUrl(String unsubToken) { + return baseUrl + "/track/unsubscribe/" + unsubToken; + } + + /** @param encodedUrl the original link, base64url-encoded without padding */ + public String clickUrl(String clickToken, String encodedUrl) { + return baseUrl + "/track/click/" + clickToken + "?t=" + encodedUrl; + } + + public String pixelUrl(String pixelToken) { + return baseUrl + "/track/open/" + pixelToken + "?cb=" + System.currentTimeMillis(); + } +} diff --git a/src/main/java/com/mailengine/mailengine/util/EmailAddresses.java b/src/main/java/com/mailengine/mailengine/util/EmailAddresses.java new file mode 100644 index 0000000..5922e10 --- /dev/null +++ b/src/main/java/com/mailengine/mailengine/util/EmailAddresses.java @@ -0,0 +1,15 @@ +package com.mailengine.mailengine.util; + +import java.util.Locale; + +/** The one spelling of an email address used for lookups: trimmed and lower-cased. */ +public final class EmailAddresses { + + private EmailAddresses() { + } + + /** @return the address trimmed and lower-cased; {@code ""} for {@code null} */ + public static String normalize(String email) { + return email == null ? "" : email.trim().toLowerCase(Locale.ROOT); + } +} diff --git a/src/main/java/com/mailengine/mailengine/worker/EmailQueueStore.java b/src/main/java/com/mailengine/mailengine/worker/EmailQueueStore.java index 2561db3..d12b293 100644 --- a/src/main/java/com/mailengine/mailengine/worker/EmailQueueStore.java +++ b/src/main/java/com/mailengine/mailengine/worker/EmailQueueStore.java @@ -3,10 +3,13 @@ import com.mailengine.mailengine.entity.EmailQueue; import com.mailengine.mailengine.entity.enums.CampaignStatus; import com.mailengine.mailengine.entity.enums.JobStatus; +import com.mailengine.mailengine.entity.enums.RecipientStatus; import com.mailengine.mailengine.entity.enums.QueueStatus; import com.mailengine.mailengine.repository.CampaignJobRepository; import com.mailengine.mailengine.repository.CampaignRepository; import com.mailengine.mailengine.repository.EmailQueueRepository; +import com.mailengine.mailengine.repository.RecipientRepository; +import com.mailengine.mailengine.service.SuppressionService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @@ -39,6 +42,8 @@ public class EmailQueueStore { private final EmailQueueRepository emailQueueRepository; private final CampaignJobRepository campaignJobRepository; private final CampaignRepository campaignRepository; + private final RecipientRepository recipientRepository; + private final SuppressionService suppressionService; /** * Claims up to {@code batchSize} emails with {@code SELECT ... FOR UPDATE SKIP LOCKED}: the row locks are held @@ -62,6 +67,30 @@ public boolean isPaused(Long campaignId) { .orElse(false); } + /** + * Whether the email may still go out. Eligibility was checked when the campaign was queued, but a long send + * can run for hours: anyone who unsubscribed, bounced or complained since then must not get it. + */ + @Transactional(readOnly = true) + public boolean stillEligible(EmailQueue queued) { + if (suppressionService.isSuppressed(queued.getToEmail())) return false; + if (queued.getRecipient() == null) return true; + // The claimed entity is detached: read the recipient's status as it is now + return recipientRepository.findById(queued.getRecipient().getId()) + .map(r -> r.getStatus() == RecipientStatus.active) + .orElse(false); + } + + /** Drops a claimed email without sending it (its recipient opted out); it is not an attempt. */ + @Transactional + public void markSkipped(Long queueId, String reason) { + emailQueueRepository.findById(queueId).ifPresent(entry -> { + entry.setStatus(QueueStatus.skipped); + entry.setErrorMessage(reason); + entry.setLockedUntil(null); + }); + } + @Transactional public void markSent(Long queueId, String messageId) { emailQueueRepository.findById(queueId).ifPresent(entry -> { @@ -108,12 +137,13 @@ public void release(Long queueId) { * several workers), then finishes the campaign if none of its emails is waiting or in flight any more. */ @Transactional - public void recordProgress(Long campaignId, int sent, int failed) { + public void recordProgress(Long campaignId, int sent, int failed, int skipped) { if (sent > 0) { campaignJobRepository.incrementSentCount(campaignId, sent); campaignRepository.incrementTotalSent(campaignId, sent); } if (failed > 0) campaignJobRepository.incrementFailedCount(campaignId, failed); + if (skipped > 0) campaignJobRepository.incrementSkippedCount(campaignId, skipped); long open = emailQueueRepository.countByCampaignIdAndStatusIn( campaignId, List.of(QueueStatus.pending, QueueStatus.sending)); diff --git a/src/main/java/com/mailengine/mailengine/worker/EmailSenderWorker.java b/src/main/java/com/mailengine/mailengine/worker/EmailSenderWorker.java index a21991a..539ed9d 100644 --- a/src/main/java/com/mailengine/mailengine/worker/EmailSenderWorker.java +++ b/src/main/java/com/mailengine/mailengine/worker/EmailSenderWorker.java @@ -2,6 +2,7 @@ import com.mailengine.mailengine.entity.EmailQueue; import com.mailengine.mailengine.service.EmailSender; +import com.mailengine.mailengine.service.TrackingUrls; import io.github.bucket4j.Bandwidth; import io.github.bucket4j.Bucket; import lombok.RequiredArgsConstructor; @@ -32,6 +33,7 @@ public class EmailSenderWorker { private final EmailQueueStore store; /** The @Primary sender: CompositeEmailSender (Resend → SES → SMTP), or MockEmailSender in mock-email. */ private final EmailSender emailSender; + private final TrackingUrls trackingUrls; @Value("${app.sending.batch-size:20}") private int batchSize; @@ -57,7 +59,7 @@ public void processEmailBatch() { List batch = store.claimBatch(batchSize); if (batch.isEmpty()) return; - Map sentAndFailedByCampaign = new LinkedHashMap<>(); + Map resultsByCampaign = new LinkedHashMap<>(); Set paused = new HashSet<>(); for (int i = 0; i < batch.size(); i++) { EmailQueue queued = batch.get(i); @@ -70,12 +72,19 @@ public void processEmailBatch() { continue; } + int[] tally = resultsByCampaign.computeIfAbsent(campaignId, id -> new int[3]); + // Checked before every email, so an opt-out during a long send takes effect at once + if (!store.stillEligible(queued)) { + store.markSkipped(queued.getId(), "Recipient opted out after the campaign was queued"); + tally[2]++; + continue; + } + if (!awaitSendSlot()) { // Shutting down: hand the rest back so the next worker sends them straight away batch.subList(i, batch.size()).forEach(rest -> store.release(rest.getId())); break; } - int[] tally = sentAndFailedByCampaign.computeIfAbsent(campaignId, id -> new int[2]); String messageId = send(queued); if (messageId != null) { store.markSent(queued.getId(), messageId); @@ -85,11 +94,11 @@ public void processEmailBatch() { } } - sentAndFailedByCampaign.forEach((campaignId, tally) -> { - if (campaignId != null) store.recordProgress(campaignId, tally[0], tally[1]); + resultsByCampaign.forEach((campaignId, tally) -> { + if (campaignId != null) store.recordProgress(campaignId, tally[0], tally[1], tally[2]); }); log.info("Worker batch done: {} claimed, campaigns {}, paused {}", batch.size(), - sentAndFailedByCampaign.keySet(), paused); + resultsByCampaign.keySet(), paused); } /** Waits until the send rate allows one more email; false if interrupted (the app is stopping). */ @@ -108,10 +117,21 @@ private boolean awaitSendSlot() { private String send(EmailQueue queued) { try { return emailSender.send(queued.getToEmail(), queued.getFromName(), queued.getFromEmail(), - queued.getSubjectLine(), queued.getHtmlContent()); + queued.getSubjectLine(), queued.getHtmlContent(), unsubscribeHeaders(queued)); } catch (RuntimeException e) { log.error("Sending email {} failed: {}", queued.getId(), e.getMessage()); return null; } } + + /** + * One-click unsubscribe (RFC 8058), which Gmail and Yahoo require of bulk senders: the mail client shows an + * "Unsubscribe" button that POSTs to the URL. + */ + private Map unsubscribeHeaders(EmailQueue queued) { + if (queued.getUnsubToken() == null) return Map.of(); + return Map.of( + "List-Unsubscribe", "<" + trackingUrls.unsubscribeUrl(queued.getUnsubToken()) + ">", + "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"); + } } diff --git a/src/main/resources/db/migration/V2__queue_skipped.sql b/src/main/resources/db/migration/V2__queue_skipped.sql new file mode 100644 index 0000000..047958d --- /dev/null +++ b/src/main/resources/db/migration/V2__queue_skipped.sql @@ -0,0 +1,7 @@ +-- An email whose recipient opted out (unsubscribe, bounce, complaint) after it was queued is not sent but +-- marked 'skipped' by the worker, and counted on the campaign's job. +ALTER TABLE email_queue DROP CONSTRAINT email_queue_status_check; +ALTER TABLE email_queue ADD CONSTRAINT email_queue_status_check + CHECK (status IN ('pending', 'sending', 'sent', 'failed', 'skipped')); + +ALTER TABLE campaign_jobs ADD COLUMN skipped_count INTEGER DEFAULT 0; diff --git a/src/test/java/com/mailengine/mailengine/integration/CampaignPipelineIntegrationTest.java b/src/test/java/com/mailengine/mailengine/integration/CampaignPipelineIntegrationTest.java index 5580637..1ca2523 100644 --- a/src/test/java/com/mailengine/mailengine/integration/CampaignPipelineIntegrationTest.java +++ b/src/test/java/com/mailengine/mailengine/integration/CampaignPipelineIntegrationTest.java @@ -27,6 +27,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; @@ -63,7 +64,7 @@ void cleanQueueAndAcceptEveryEmail() { // Each test starts with an empty outbox, so the worker only ever sees this test's emails jdbc.update("delete from email_queue"); jdbc.update("update campaign_jobs set status = 'completed' where status in ('processing', 'paused')"); - when(emailSender.send(anyString(), anyString(), anyString(), anyString(), anyString())) + when(emailSender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())) .thenAnswer(i -> "msg-" + messageIds.incrementAndGet()); } @@ -120,7 +121,7 @@ void emailsOfTwoCampaignsInOneBatchAreCountedForTheirOwnCampaign() { void pausingMidBatchLeavesNoEmailStuckAndResumeSendsTheRest() { long id = sentCampaign(5); AtomicInteger calls = new AtomicInteger(); - when(emailSender.send(anyString(), anyString(), anyString(), anyString(), anyString())).thenAnswer(i -> { + when(emailSender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())).thenAnswer(i -> { if (calls.incrementAndGet() == 2) sendingService.pauseCampaign(id); // the user clicks Pause return "msg-" + messageIds.incrementAndGet(); }); @@ -154,7 +155,7 @@ void pausedCampaignDoesNotBlockOtherCampaigns() { void emailRetriedAfterAFailureIsNotCountedAsFailed() { long id = sentCampaign(2); AtomicInteger calls = new AtomicInteger(); - when(emailSender.send(anyString(), anyString(), anyString(), anyString(), anyString())) + when(emailSender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())) .thenAnswer(i -> calls.incrementAndGet() == 1 ? null : "msg-" + messageIds.incrementAndGet()); worker.processEmailBatch(); @@ -169,7 +170,7 @@ void emailRetriedAfterAFailureIsNotCountedAsFailed() { @Test void emailThatFailsThreeTimesIsCountedOnceAndAnAllFailedCampaignIsFailed() { long id = sentCampaign(1); - when(emailSender.send(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(null); + when(emailSender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())).thenReturn(null); drainQueue(); @@ -207,7 +208,7 @@ void claimedEmailsAreNotClaimedAgainWhileTheClaimIsValid() { @Test void failedEmailWaitsForItsRetryDelay() { long id = sentCampaign(1); - when(emailSender.send(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(null); + when(emailSender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())).thenReturn(null); worker.processEmailBatch(); // attempt 1 fails: retry in 2 minutes worker.processEmailBatch(); // too early: must not try again @@ -239,6 +240,74 @@ void sendingTheSameCampaignTwiceAtOnceQueuesItOnce() throws Exception { } } + // ── Opt-outs and recipient data ───────────────────────────────────────── + + @Test + void recipientWhoUnsubscribesMidCampaignIsSkippedAndTheCampaignStillFinishes() throws Exception { + long id = sentCampaign(3); + String token = jdbc.queryForObject( + "select unsub_token from email_queue where campaign_id = ? order by id limit 1", String.class, id); + String email = jdbc.queryForObject("select to_email from email_queue where unsub_token = ?", String.class, token); + + // One-click unsubscribe from the mail client, after queueing but before the worker reaches the email + assertThat(mvc.perform(post("/track/unsubscribe/{token}", token) + .contentType(MediaType.APPLICATION_FORM_URLENCODED).content("List-Unsubscribe=One-Click")) + .andReturn().getResponse().getStatus()).isEqualTo(200); + drainQueue(); + + assertThat(countQueue(id, "skipped")).isEqualTo(1); + assertThat(countQueue(id, "sent")).isEqualTo(2); + assertThat(campaignStatus(id)).isEqualTo("sent"); + assertThat(job(id)).containsEntry("status", "completed").containsEntry("sent_count", 2) + .containsEntry("skipped_count", 1); + assertThat(sendingService.getJobStatus(id).getProgress()).isEqualTo(100); + assertThat(jdbc.queryForObject("select reason from suppression_list where email = ?", String.class, email)) + .as("an unsubscribe from the email also suppresses the address").isEqualTo("unsubscribed"); + } + + @Test + void openingTheUnsubscribeLinkOnlyAsksForConfirmation() throws Exception { + long id = sentCampaign(1); + String token = jdbc.queryForObject("select unsub_token from email_queue where campaign_id = ?", String.class, id); + long recipientId = jdbc.queryForObject("select recipient_id from email_queue where campaign_id = ?", Long.class, id); + + // What a link scanner does: a GET must not unsubscribe anyone + var page = mvc.perform(get("/track/unsubscribe/{token}", token)).andReturn().getResponse(); + + assertThat(page.getStatus()).isEqualTo(200); + assertThat(page.getContentAsString()).contains("

"); + assertThat(recipientRepository.findById(recipientId).orElseThrow().getStatus()).isEqualTo(RecipientStatus.active); + } + + @Test + void unsubscribingTwiceKeepsOneSuppressionEntry() throws Exception { + long id = sentCampaign(1); + String token = jdbc.queryForObject("select unsub_token from email_queue where campaign_id = ?", String.class, id); + String email = jdbc.queryForObject("select to_email from email_queue where campaign_id = ?", String.class, id); + + mvc.perform(post("/track/unsubscribe/{token}", token)); + assertThat(mvc.perform(post("/track/unsubscribe/{token}", token)).andReturn().getResponse().getStatus()) + .isEqualTo(200); + + assertThat(jdbc.queryForObject("select count(*) from suppression_list where email = ?", Integer.class, email)) + .isEqualTo(1); + } + + @Test + void recipientDataCannotAddMarkupToTheEmail() { + long id = draftCampaign(1); + jdbc.update(""" + update recipients set first_name = 'x' + where id = (select recipient_id from recipient_list_members m + join campaign_recipient_lists c on c.recipient_list_id = m.recipient_list_id + where c.campaign_id = ?)""", id); + sendingService.sendCampaign(id); + + String html = jdbc.queryForObject("select html_content from email_queue where campaign_id = ?", String.class, id); + assertThat(html).contains("Hi <a href="https://evil.test">x</a>") + .doesNotContain("evil.test\">"); + } + // ── Scheduling ────────────────────────────────────────────────────────── @Test @@ -502,7 +571,7 @@ private String campaignStatus(long id) { } private Map job(long campaignId) { - return jdbc.queryForMap("select status, sent_count, failed_count from campaign_jobs where campaign_id = ?", + return jdbc.queryForMap("select status, sent_count, failed_count, skipped_count from campaign_jobs where campaign_id = ?", campaignId); } diff --git a/src/test/java/com/mailengine/mailengine/service/EmailHeadersTest.java b/src/test/java/com/mailengine/mailengine/service/EmailHeadersTest.java new file mode 100644 index 0000000..b017320 --- /dev/null +++ b/src/test/java/com/mailengine/mailengine/service/EmailHeadersTest.java @@ -0,0 +1,65 @@ +package com.mailengine.mailengine.service; + +import jakarta.mail.Session; +import jakarta.mail.internet.MimeMessage; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.mail.javamail.JavaMailSenderImpl; +import software.amazon.awssdk.services.ses.SesClient; +import software.amazon.awssdk.services.ses.model.SendRawEmailRequest; +import software.amazon.awssdk.services.ses.model.SendRawEmailResponse; + +import java.io.ByteArrayInputStream; +import java.util.Map; +import java.util.Properties; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +/** Extra headers (List-Unsubscribe) reach the message whichever sender delivers it. */ +class EmailHeadersTest { + + private static final Map HEADERS = Map.of( + "List-Unsubscribe", "", + "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"); + + @Test + void sesSendsARawMessageWithTheHeaders() throws Exception { + SesClient ses = mock(SesClient.class); + when(ses.sendRawEmail(any(SendRawEmailRequest.class))) + .thenReturn(SendRawEmailResponse.builder().messageId("ses-1").build()); + + String id = new SesEmailSender(ses).send("to@example.test", "Team", "team@example.test", "Hi", + "

Hello

", HEADERS); + + assertThat(id).as("the SES message id still comes back for webhook matching").isEqualTo("ses-1"); + ArgumentCaptor request = ArgumentCaptor.forClass(SendRawEmailRequest.class); + verify(ses).sendRawEmail(request.capture()); + MimeMessage sent = new MimeMessage(Session.getInstance(new Properties()), + new ByteArrayInputStream(request.getValue().rawMessage().data().asByteArray())); + assertThat(sent.getHeader("List-Unsubscribe", null)).isEqualTo(""); + assertThat(sent.getHeader("List-Unsubscribe-Post", null)).isEqualTo("List-Unsubscribe=One-Click"); + assertThat(sent.getHeader("From", null)).isEqualTo("Team "); + assertThat(sent.getHeader("To", null)).isEqualTo("to@example.test"); + assertThat(sent.getSubject()).isEqualTo("Hi"); + java.io.ByteArrayOutputStream body = new java.io.ByteArrayOutputStream(); + sent.writeTo(body); + assertThat(body.toString()).contains("

Hello

"); + } + + @Test + void smtpSetsTheHeaders() throws Exception { + JavaMailSenderImpl mail = spy(new JavaMailSenderImpl()); + mail.setUsername("user"); + doNothing().when(mail).send(any(MimeMessage.class)); + + new SmtpEmailSender(mail).send("to@example.test", "Team", "team@example.test", "Hi", "

Hello

", HEADERS); + + ArgumentCaptor sent = ArgumentCaptor.forClass(MimeMessage.class); + verify(mail).send(sent.capture()); + assertThat(sent.getValue().getHeader("List-Unsubscribe", null)) + .isEqualTo(""); + assertThat(sent.getValue().getHeader("List-Unsubscribe-Post", null)).isEqualTo("List-Unsubscribe=One-Click"); + } +} diff --git a/src/test/java/com/mailengine/mailengine/service/SesEventServiceTest.java b/src/test/java/com/mailengine/mailengine/service/SesEventServiceTest.java index 2299a03..716627d 100644 --- a/src/test/java/com/mailengine/mailengine/service/SesEventServiceTest.java +++ b/src/test/java/com/mailengine/mailengine/service/SesEventServiceTest.java @@ -5,7 +5,6 @@ import com.mailengine.mailengine.entity.Campaign; import com.mailengine.mailengine.entity.EmailQueue; import com.mailengine.mailengine.entity.Recipient; -import com.mailengine.mailengine.entity.SuppressionList; import com.mailengine.mailengine.entity.TrackingEvent; import com.mailengine.mailengine.entity.enums.RecipientStatus; import com.mailengine.mailengine.repository.EmailQueueRepository; @@ -16,7 +15,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; @@ -36,13 +34,15 @@ class SesEventServiceTest { @Mock TrackingEventRepository trackingEventRepository; @Mock RecipientRepository recipientRepository; @Mock SuppressionListRepository suppressionListRepository; - @InjectMocks SesEventService service; + SesEventService service; private final ObjectMapper json = new ObjectMapper(); private Recipient recipient; @BeforeEach void anEmailWasSentToAnn() { + service = new SesEventService(emailQueueRepository, trackingEventRepository, recipientRepository, + new SuppressionService(suppressionListRepository, recipientRepository)); recipient = new Recipient(); recipient.setId(5L); recipient.setEmail("ann@x.test"); @@ -61,8 +61,7 @@ void permanentBounceStopsAllMailToTheAddress() throws Exception { "bounce":{"bounceType":"Permanent","bouncedRecipients":[],"recipients":[{"emailAddress":"Ann@X.test"}]}}""")); assertThat(recipient.getStatus()).isEqualTo(RecipientStatus.bounced); - assertThat(suppressed()).extracting(SuppressionList::getEmail, SuppressionList::getReason) - .containsExactly("ann@x.test", "bounced"); + assertThat(suppressed()).containsExactly("ann@x.test", "bounced"); assertThat(recordedType()).isEqualTo("bounce"); } @@ -73,7 +72,7 @@ void transientBounceIsOnlyRecorded() throws Exception { "bounce":{"bounceType":"Transient","recipients":[{"emailAddress":"ann@x.test"}]}}""")); assertThat(recipient.getStatus()).isEqualTo(RecipientStatus.active); - verify(suppressionListRepository, never()).save(any()); + verify(suppressionListRepository, never()).insertIfAbsent(any(), any()); assertThat(recordedType()).isEqualTo("bounce"); } @@ -84,18 +83,7 @@ void complaintStopsAllMailToTheAddress() throws Exception { "complaint":{"recipients":[{"emailAddress":"ann@x.test"}]}}""")); assertThat(recipient.getStatus()).isEqualTo(RecipientStatus.complained); - assertThat(suppressed().getReason()).isEqualTo("complaint"); - } - - @Test - void alreadySuppressedAddressIsNotAddedTwice() throws Exception { - when(suppressionListRepository.existsByEmail("ann@x.test")).thenReturn(true); - - service.handle(event(""" - {"notificationType":"Complaint","mail":{"messageId":"m-1"}, - "complaint":{"recipients":[{"emailAddress":"ann@x.test"}]}}""")); - - verify(suppressionListRepository, never()).save(any()); + assertThat(suppressed()[1]).isEqualTo("complaint"); } @Test @@ -107,7 +95,7 @@ void unsubscribedRecipientKeepsTheirStatusButIsStillSuppressed() throws Exceptio "bounce":{"bounceType":"Permanent","recipients":[{"emailAddress":"ann@x.test"}]}}""")); assertThat(recipient.getStatus()).isEqualTo(RecipientStatus.unsubscribed); - assertThat(suppressed().getReason()).isEqualTo("bounced"); + assertThat(suppressed()[1]).isEqualTo("bounced"); } @Test @@ -118,7 +106,7 @@ void bounceForAnUnknownMessageStillSuppressesTheAddress() throws Exception { verify(trackingEventRepository, never()).save(any()); assertThat(recipient.getStatus()).isEqualTo(RecipientStatus.bounced); - assertThat(suppressed().getEmail()).isEqualTo("ann@x.test"); + assertThat(suppressed()[0]).isEqualTo("ann@x.test"); } @Test @@ -129,7 +117,7 @@ void deliveryIsOnlyRecorded() throws Exception { assertThat(recordedType()).isEqualTo("delivery"); assertThat(recipient.getStatus()).isEqualTo(RecipientStatus.active); - verify(suppressionListRepository, never()).save(any()); + verify(suppressionListRepository, never()).insertIfAbsent(any(), any()); } @Test @@ -143,10 +131,12 @@ private JsonNode event(String text) throws Exception { return json.readTree(text); } - private SuppressionList suppressed() { - ArgumentCaptor c = ArgumentCaptor.forClass(SuppressionList.class); - verify(suppressionListRepository).save(c.capture()); - return c.getValue(); + /** The address and reason added to the suppression list. */ + private String[] suppressed() { + ArgumentCaptor email = ArgumentCaptor.forClass(String.class); + ArgumentCaptor reason = ArgumentCaptor.forClass(String.class); + verify(suppressionListRepository).insertIfAbsent(email.capture(), reason.capture()); + return new String[]{email.getValue(), reason.getValue()}; } private String recordedType() { diff --git a/src/test/java/com/mailengine/mailengine/service/SuppressionServiceTest.java b/src/test/java/com/mailengine/mailengine/service/SuppressionServiceTest.java new file mode 100644 index 0000000..589f14f --- /dev/null +++ b/src/test/java/com/mailengine/mailengine/service/SuppressionServiceTest.java @@ -0,0 +1,102 @@ +package com.mailengine.mailengine.service; + +import com.mailengine.mailengine.dto.request.CreateRecipientRequest; +import com.mailengine.mailengine.entity.Recipient; +import com.mailengine.mailengine.entity.enums.RecipientStatus; +import com.mailengine.mailengine.exception.BadRequestException; +import com.mailengine.mailengine.repository.RecipientListMemberRepository; +import com.mailengine.mailengine.repository.RecipientListRepository; +import com.mailengine.mailengine.repository.RecipientRepository; +import com.mailengine.mailengine.repository.SuppressionListRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +/** Opt-outs: one spelling of each address, and both the recipient status and the suppression list. */ +@ExtendWith(MockitoExtension.class) +class SuppressionServiceTest { + + @Mock SuppressionListRepository suppressionListRepository; + @Mock RecipientRepository recipientRepository; + @Mock RecipientListRepository recipientListRepository; + @Mock RecipientListMemberRepository memberRepository; + SuppressionService suppression; + + @BeforeEach + void setUp() { + suppression = new SuppressionService(suppressionListRepository, recipientRepository); + } + + @Test + void addressesAreNormalisedBeforeLookupAndInsert() { + when(suppressionListRepository.existsByEmail("ann@x.test")).thenReturn(true); + + assertThat(suppression.isSuppressed(" Ann@X.test ")).isTrue(); + suppression.suppress(" Ann@X.TEST", "unsubscribed"); + + verify(suppressionListRepository).insertIfAbsent("ann@x.test", "unsubscribed"); + } + + @Test + void blankAddressIsNeverSuppressed() { + assertThat(suppression.isSuppressed(null)).isFalse(); + suppression.suppress(" ", "bounced"); + + verifyNoInteractions(suppressionListRepository); + } + + @Test + void optOutChangesOnlyAnActiveRecipientsStatus() { + Recipient active = recipient(RecipientStatus.active); + Recipient bounced = recipient(RecipientStatus.bounced); + + suppression.optOut(active, "a@x.test", RecipientStatus.unsubscribed, "unsubscribed"); + suppression.optOut(bounced, "b@x.test", RecipientStatus.unsubscribed, "unsubscribed"); + + assertThat(active.getStatus()).isEqualTo(RecipientStatus.unsubscribed); + assertThat(bounced.getStatus()).as("a bounce stays a bounce").isEqualTo(RecipientStatus.bounced); + verify(suppressionListRepository).insertIfAbsent("a@x.test", "unsubscribed"); + verify(suppressionListRepository).insertIfAbsent("b@x.test", "unsubscribed"); + } + + @Test + void addingARecipientInAnotherCaseCannotBypassAnOptOut() { + RecipientService recipients = new RecipientService( + recipientRepository, recipientListRepository, memberRepository, suppression); + when(suppressionListRepository.existsByEmail("foo@x.test")).thenReturn(true); + CreateRecipientRequest request = new CreateRecipientRequest(); + ReflectionTestUtils.setField(request, "email", "Foo@X.test"); + + assertThatThrownBy(() -> recipients.addRecipient(1L, request)).isInstanceOf(BadRequestException.class); + verify(recipientRepository, never()).save(any()); + } + + @Test + void complainedRecipientCannotBeAddedBack() { + RecipientService recipients = new RecipientService( + recipientRepository, recipientListRepository, memberRepository, suppression); + when(recipientRepository.findByEmail("c@x.test")).thenReturn(Optional.of(recipient(RecipientStatus.complained))); + CreateRecipientRequest request = new CreateRecipientRequest(); + ReflectionTestUtils.setField(request, "email", "c@x.test"); + + assertThatThrownBy(() -> recipients.addRecipient(1L, request)).isInstanceOf(BadRequestException.class); + verify(recipientRepository, never()).save(any()); + } + + private static Recipient recipient(RecipientStatus status) { + Recipient r = new Recipient(); + r.setEmail("r@x.test"); + r.setStatus(status); + return r; + } +} diff --git a/src/test/java/com/mailengine/mailengine/worker/EmailSenderWorkerTest.java b/src/test/java/com/mailengine/mailengine/worker/EmailSenderWorkerTest.java index c9e3420..a469c53 100644 --- a/src/test/java/com/mailengine/mailengine/worker/EmailSenderWorkerTest.java +++ b/src/test/java/com/mailengine/mailengine/worker/EmailSenderWorkerTest.java @@ -3,18 +3,23 @@ import com.mailengine.mailengine.entity.Campaign; import com.mailengine.mailengine.entity.EmailQueue; import com.mailengine.mailengine.service.EmailSender; +import com.mailengine.mailengine.service.TrackingUrls; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; import java.util.ArrayList; import java.util.List; +import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; @@ -31,8 +36,9 @@ class EmailSenderWorkerTest { @BeforeEach void setUp() { - worker = new EmailSenderWorker(store, sender); + worker = new EmailSenderWorker(store, sender, new TrackingUrls("https://mail.example.test")); ReflectionTestUtils.setField(worker, "batchSize", 20); + lenient().when(store.stillEligible(any())).thenReturn(true); } @Test @@ -42,14 +48,14 @@ void emptyQueueDoesNothing() { worker.processEmailBatch(); verifyNoInteractions(sender); - verify(store, never()).recordProgress(anyLong(), anyInt(), anyInt()); + verify(store, never()).recordProgress(anyLong(), anyInt(), anyInt(), anyInt()); } @Test void sendingIsCappedAtTheConfiguredRate() { worker.setRatePerSecond(4); when(store.claimBatch(20)).thenReturn(batch(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)); - when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn("id"); + when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())).thenReturn("id"); long start = System.nanoTime(); worker.processEmailBatch(); @@ -57,14 +63,14 @@ void sendingIsCappedAtTheConfiguredRate() { // 4 go straight away, the other 4 at 4 per second assertThat(millis).isGreaterThanOrEqualTo(800); - verify(store).recordProgress(1L, 8, 0); + verify(store).recordProgress(1L, 8, 0, 0); } @Test void anInterruptedWorkerHandsTheRestOfTheBatchBack() { worker.setRatePerSecond(1); when(store.claimBatch(20)).thenReturn(batch(1L, 1L, 1L)); - when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString())).thenAnswer(i -> { + when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())).thenAnswer(i -> { Thread.currentThread().interrupt(); // the app is stopping return "id"; }); @@ -72,7 +78,7 @@ void anInterruptedWorkerHandsTheRestOfTheBatchBack() { worker.processEmailBatch(); Thread.interrupted(); // clear the flag for the next test - verify(sender, times(1)).send(anyString(), anyString(), anyString(), anyString(), anyString()); + verify(sender, times(1)).send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap()); verify(store).release(2L); verify(store).release(3L); } @@ -80,40 +86,40 @@ void anInterruptedWorkerHandsTheRestOfTheBatchBack() { @Test void resultsAreCountedPerCampaign() { when(store.claimBatch(20)).thenReturn(batch(1L, 1L, 2L, 2L, 2L)); - when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn("id"); + when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())).thenReturn("id"); worker.processEmailBatch(); - verify(store).recordProgress(1L, 2, 0); - verify(store).recordProgress(2L, 3, 0); + verify(store).recordProgress(1L, 2, 0, 0); + verify(store).recordProgress(2L, 3, 0, 0); } @Test void failureThatWillBeRetriedIsNotCounted() { when(store.claimBatch(20)).thenReturn(batch(1L, 1L)); - when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(null, "id"); + when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())).thenReturn(null, "id"); when(store.markFailed(anyLong(), anyString())).thenReturn(false); // attempts left worker.processEmailBatch(); - verify(store).recordProgress(1L, 1, 0); + verify(store).recordProgress(1L, 1, 0, 0); } @Test void finalFailureIsCounted() { when(store.claimBatch(20)).thenReturn(batch(1L)); - when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(null); + when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())).thenReturn(null); when(store.markFailed(anyLong(), anyString())).thenReturn(true); worker.processEmailBatch(); - verify(store).recordProgress(1L, 0, 1); + verify(store).recordProgress(1L, 0, 1, 0); } @Test void senderThatThrowsIsTreatedAsAFailedAttempt() { when(store.claimBatch(20)).thenReturn(batch(1L, 1L)); - when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString())) + when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())) .thenThrow(new IllegalStateException("network down")).thenReturn("id"); worker.processEmailBatch(); @@ -128,7 +134,7 @@ void pauseMidBatchHandsTheRestBackAndOtherCampaignsCarryOn() { when(store.claimBatch(20)).thenReturn(batch); when(store.isPaused(1L)).thenReturn(false, true); // paused after the first email when(store.isPaused(2L)).thenReturn(false); - when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn("id"); + when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())).thenReturn("id"); worker.processEmailBatch(); @@ -137,8 +143,40 @@ void pauseMidBatchHandsTheRestBackAndOtherCampaignsCarryOn() { verify(store).release(3L); verify(store).markSent(4L, "id"); verify(store, times(2)).isPaused(1L); // asked once, then remembered for the rest of the batch - verify(store).recordProgress(1L, 1, 0); - verify(store).recordProgress(2L, 1, 0); + verify(store).recordProgress(1L, 1, 0, 0); + verify(store).recordProgress(2L, 1, 0, 0); + } + + @Test + void recipientWhoOptedOutSinceQueueingIsSkippedNotSent() { + List batch = batch(1L, 1L, 1L); + when(store.claimBatch(20)).thenReturn(batch); + when(store.stillEligible(batch.get(1))).thenReturn(false); // unsubscribed mid-campaign + when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())).thenReturn("id"); + + worker.processEmailBatch(); + + verify(sender, times(2)).send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap()); + verify(store).markSkipped(eq(2L), anyString()); + verify(store, never()).markSent(eq(2L), anyString()); + verify(store).recordProgress(1L, 2, 0, 1); + } + + @Test + void campaignEmailsCarryOneClickUnsubscribeHeaders() { + List batch = batch(1L); + batch.get(0).setUnsubToken("tok-123"); + when(store.claimBatch(20)).thenReturn(batch); + when(sender.send(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap())).thenReturn("id"); + + worker.processEmailBatch(); + + @SuppressWarnings("unchecked") + ArgumentCaptor> headers = ArgumentCaptor.forClass(Map.class); + verify(sender).send(anyString(), anyString(), anyString(), anyString(), anyString(), headers.capture()); + assertThat(headers.getValue()).containsEntry( + "List-Unsubscribe", "") + .containsEntry("List-Unsubscribe-Post", "List-Unsubscribe=One-Click"); } private List batch(Long... campaignIds) {