Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
```

---
Expand Down Expand Up @@ -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.
Expand All @@ -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) |
Expand Down Expand Up @@ -517,7 +519,7 @@ Authorization: Bearer <jwt-token>
| 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 |

Expand Down Expand Up @@ -578,7 +580,8 @@ Authorization: Bearer <jwt-token>
|---|---|---|
| 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)

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -20,7 +23,8 @@
* <ul>
* <li>{@code GET /track/open/{pixelToken}} — logs open event, returns 1×1 PNG</li>
* <li>{@code GET /track/click/{clickToken}} — logs click event, 302-redirects to original URL</li>
* <li>{@code GET /track/unsubscribe/{unsubToken}} — marks recipient unsubscribed, shows confirmation HTML</li>
* <li>{@code GET /track/unsubscribe/{unsubToken}} — confirmation page; {@code POST} (its button, or one-click
* from the mail provider) unsubscribes</li>
* </ul>
*
* <p>Keep these endpoints as lean as possible. Email clients time out quickly
Expand Down Expand Up @@ -103,38 +107,52 @@ public ResponseEntity<Void> 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.
*
* <p>Every outgoing email includes an unsubscribe link:
* <pre>
* &lt;a href="https://api.yourapp.com/track/unsubscribe/{unsubToken}"&gt;Unsubscribe&lt;/a&gt;
* </pre>
* 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.
* <p>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.
*
* <p>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<String> trackUnsubscribe(@PathVariable String unsubToken) {
String companyName = trackingService.handleUnsubscribe(unsubToken);
public ResponseEntity<String> 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?",
"<p>Click below to stop receiving these emails.</p>"
+ "<form method=\"post\" action=\"" + action + "\">"
+ "<button type=\"submit\">Unsubscribe</button></form>"));
}

// 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).
*
* <p>POST /track/unsubscribe/{unsubToken}
*/
@PostMapping(value = "/unsubscribe/{unsubToken}", produces = MediaType.TEXT_HTML_VALUE)
public ResponseEntity<String> unsubscribe(@PathVariable String unsubToken) {
String companyName = trackingService.handleUnsubscribe(unsubToken);
if (companyName == null) {
companyName = "this mailing list";
}
return ResponseEntity.ok(page("You have been unsubscribed",
"<p>You will no longer receive emails from <strong>" + HtmlUtils.htmlEscape(companyName)
+ "</strong>.</p>"));
}

// 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 """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Unsubscribed</title>
<title>%s</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
Expand All @@ -155,17 +173,19 @@ public ResponseEntity<String> trackUnsubscribe(@PathVariable String unsubToken)
}
h1 { color: #111827; font-size: 24px; margin-bottom: 12px; }
p { color: #6b7280; font-size: 16px; line-height: 1.6; }
button {
font-size: 16px; padding: 10px 24px; border: 0; border-radius: 8px;
background: #111827; color: white; cursor: pointer;
}
</style>
</head>
<body>
<div class="card">
<h1>You have been unsubscribed</h1>
<p>You will no longer receive emails from <strong>%s</strong>.</p>
<h1>%s</h1>
%s
</div>
</body>
</html>
""".formatted(companyName);

return ResponseEntity.ok(html);
""".formatted(heading, heading, bodyHtml);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package com.mailengine.mailengine.entity.enums;

public enum QueueStatus {
pending, sending, sent, failed
pending, sending, sent, failed, skipped
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,14 @@ public interface CampaignJobRepository extends JpaRepository<CampaignJob, Long>
WHERE j.campaign.id = :campaignId
""")
void incrementFailedCount(@Param("campaignId") Long campaignId, @Param("count") int count);
}

// 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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<SuppressionList, Long> {
boolean existsByEmail(String email);
Optional<SuppressionList> 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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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;

Expand All @@ -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())
Expand Down Expand Up @@ -226,7 +227,7 @@ private List<Recipient> 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);
Expand All @@ -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) {
Expand All @@ -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 + "\""));
}
Expand All @@ -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);
Expand All @@ -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 = "<img src=\"" + pixelUrl + "\" width=\"1\" height=\"1\" "
+ "alt=\"\" style=\"display:none;\" />";
return injectBeforeClosingBody(html, pixelTag);
Expand All @@ -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;
Expand Down
Loading
Loading