Skip to content

About

A self-hosted email marketing platform for sending bulk campaigns, tracking engagement, and analyzing results. Built with Spring Boot 3.5 / Java 21 / PostgreSQL.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

MailEngine

A self-hosted email marketing platform for sending bulk campaigns, tracking engagement, and analysing results. Built with Spring Boot 3.5 / Java 21 / PostgreSQL.


Table of Contents

  1. What It Does
  2. Tech Stack
  3. Architecture
  4. Project Structure
  5. Prerequisites
  6. Local Setup
  7. Environment Variables
  8. Database
  9. Running the App
  10. Testing
  11. Mock Email Mode
  12. Roles & Permissions
  13. API Reference
  14. Core Concepts
  15. Adding a New Feature
  16. Deployment

What It Does

MailEngine lets you:

  • Build and manage recipient lists (manually or via CSV / XLSX bulk import)
  • Design email templates (raw HTML or visual editor JSON)
  • Create campaigns and send or schedule them
  • Track opens, clicks, unsubscribes, bounces, and complaints in real time
  • View analytics dashboards broken down by device, geography, and link performance
  • Score recipients by engagement using an RFM-style model

Tech Stack

Layer Technology
Language Java 21
Framework Spring Boot 3.5.13
Build Gradle 8
Database PostgreSQL
Migrations Flyway
Auth JWT (HMAC-SHA256 via jjwt 0.12)
ORM Spring Data JPA / Hibernate
Email — primary Resend REST API
Email — fallback 1 AWS SES SDK v2
Email — fallback 2 SMTP (JavaMailSender)
File storage AWS S3
Bounce / complaint webhooks AWS SNS → SES
IP geolocation MaxMind GeoIP2 (GeoLite2 database file, looked up offline)
User-Agent parsing Yauaa 7.28
CSV parsing OpenCSV 5.9
Excel parsing Apache POI 5.5
Rate limiting Bucket4j 8.10 (worker send rate, public auth endpoints)
Caching Caffeine via Spring Cache (analytics queries)
API docs SpringDoc / Swagger UI
Testing JUnit 6, Mockito, AssertJ, Spring Security Test, Testcontainers (PostgreSQL)
Container Docker (multi-stage build, runs as a non-root user)
CI GitHub Actions: all test suites and the Docker build on every pull request and push to main

Architecture

                         ┌─────────────────────────────────────┐
                         │           REST API (port 8080)      │
                         │                                     │
          JWT Auth ──►   │  Controllers (11 files)             │
                         │  GlobalExceptionHandler             │
                         └──────────────┬──────────────────────┘
                                        │
                         ┌──────────────▼──────────────────────┐
                         │           Service Layer             │
                         │                                     │
                         │  AuthService  CampaignService       │
                         │  CampaignSendingService             │
                         │  RecipientService  TrackingService  │
                         │  AnalyticsService  FileUploadService│
                         │  TemplateService   EmailService     │
                         └──────────────┬──────────────────────┘
                                        │
                  ┌─────────────────────┼──────────────────┐
                  │                     │                  │
      ┌───────────▼──────┐  ┌───────────▼──────┐  ┌───────▼────────┐
      │  Repository Layer │  │  EmailSender     │  │  External APIs │
      │  (Spring Data JPA)│  │  (Composite)     │  │                │
      │                  │  │  1. Resend        │  │  MaxMind DB    │
      │  PostgreSQL       │  │  2. AWS SES       │  │  Yauaa (UA)   │
      │  (Flyway schema)  │  │  3. SMTP          │  │  AWS S3        │
      └──────────────────┘  └──────────────────┘  └────────────────┘

Background:
  EmailSenderWorker            ──► polls email_queue every 3 s (SELECT … FOR UPDATE SKIP LOCKED)
  ScheduledCampaignDispatcher  ──► starts scheduled campaigns that are due (checks every 60 s)
  EngagementScoreService       ──► recalculates engagement scores nightly at 02:00
  PendingUploadCleanup         ──► hourly, deletes upload files nobody mapped within a day
  Import pool                  ──► CSV / XLSX / XLS imports (see File Import)

Inbound webhooks:
  AWS SNS  ──►  POST /webhooks/ses  ──►  SesWebhookController

Public tracking (no auth):
  Email client  ──►  GET /track/open/{token}       (1×1 PNG pixel)
                ──►  GET /track/click/{token}      (302 redirect)
                ──►  GET /track/unsubscribe/{token} (confirmation page)
                ──►  POST /track/unsubscribe/{token} (unsubscribe; also one-click)

Project Structure

src/main/java/com/mailengine/mailengine/
├── config/           # Spring beans: AwsConfig, MailConfig, OpenApiConfig, CacheConfig, ImportExecutorConfig, JPA auditing
├── controller/       # REST controllers (one file per resource)
├── dto/
│   ├── request/      # Inbound JSON bodies
│   └── response/     # Outbound JSON bodies
├── entity/           # JPA entity classes (mapped to DB tables)
├── exception/        # Custom exceptions + GlobalExceptionHandler
├── repository/       # Spring Data JPA interfaces
├── security/         # SecurityConfig (roles, CORS), JwtService, JwtAuthFilter, AuthRateLimitFilter,
│                     #   RateLimiter, SecurityUtils, TokenHashing
├── service/          # Business logic, including the EmailSender implementations
│                     #   (Resend / SES / SMTP / Mock, combined by CompositeEmailSender)
├── util/             # SnsMessageVerifier (checks AWS SNS webhook signatures)
└── worker/           # EmailSenderWorker, EmailQueueStore, ScheduledCampaignDispatcher

src/main/resources/
├── application.yaml          # All config (reads from environment variables)
├── db/migration/             # Flyway SQL migrations (V1 is the full schema)
└── templates/                # CSV / XLSX import templates served at /template/csv and /template/xlsx

Dockerfile                    # Multi-stage image build (see Running the App)
.github/workflows/ci.yml      # CI: test suites + Docker build

Prerequisites

Install these before running the project locally:

Tool Version Notes
Java JDK 21 java -version to check
Gradle 8 (wrapper included) Use ./gradlew — no global install needed
PostgreSQL 14+ Must have a running instance
Docker any recent Needed for the integration and scale tests (Testcontainers) and to run the app as a container
Git any —

Optional but recommended for full functionality:

Tool Why
Resend account Primary email sending
AWS account SES (email fallback), S3 (image storage), SNS (bounce/complaint webhooks)
MaxMind GeoLite2 database IP → country/city on open and click events (free account, offline file)
ngrok Expose local server so AWS SNS and email tracking links work

Local Setup

1. Clone the repo

git clone <repo-url>
cd mailengine

2. Create the database

psql -U postgres
CREATE USER mailengine_user WITH PASSWORD 'your-password';
CREATE DATABASE mailengine OWNER mailengine_user;
\q

Making the user the database's owner lets Flyway create tables. (GRANT ALL PRIVILEGES ON DATABASE alone isn't enough on PostgreSQL 15+, where ordinary users can no longer create tables in the public schema.)

3. Set up environment variables

Copy the example file and fill in your values:

cp .env.example .env

Open .env and fill in at minimum the required variables (see Environment Variables below). For local development you can skip AWS credentials by enabling mock email mode.

4. Generate a JWT secret

openssl rand -base64 32

Paste the output into JWT_SECRET in your .env.

5. Run the application

./gradlew bootRun

Flyway runs automatically on startup and applies all migrations in src/main/resources/db/migration/. The database schema will be created from scratch on first run.

6. Verify it started

http://localhost:8080/ready          → "OK"
http://localhost:8080/swagger-ui.html → API docs

7. Log in with the seeded admin account

Migration V1 seeds a default admin user:

Email:    admin@mailengine.internal
Password: ChangeMe123!

The first thing you must do is change this password. The account has mustChangePwd = true, which means the JWT filter blocks all endpoints except POST /api/auth/change-password until you do.

# 1. Log in
curl -X POST http://localhost:8080/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@mailengine.internal","password":"ChangeMe123!"}'

# 2. Change password (use the token from step 1)
curl -X POST http://localhost:8080/api/auth/change-password \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"currentPassword":"ChangeMe123!","newPassword":"YourNewPassword!"}'

Environment Variables

The app reads all configuration from environment variables via .env (loaded by spring-dotenv). There is no application-local.yaml — .env is the only file you need to edit.

Required (app will not start without these)

Variable Example Description
DB_HOST localhost PostgreSQL host
DB_PORT 5432 PostgreSQL port
DB_NAME mailengine Database name
DB_USERNAME mailengine_user Database user
DB_PASSWORD secret Database password
JWT_SECRET (32-char base64 string) HMAC signing key for JWTs. Generate with openssl rand -base64 32
JWT_EXPIRATION 86400000 Token TTL in milliseconds (86400000 = 24 h)
APP_BASE_URL http://localhost:8080 Base URL used to build tracking links inside emails, and the server Swagger UI calls. Must be publicly reachable by email clients. Use your ngrok URL locally.
AWS_FROM_EMAIL hello@yourdomain.com Sender address for transactional emails (invites, password resets). Must be verified with your sender.

Email sending

To send real email, configure at least one of the three senders. The CompositeEmailSender tries them in order: Resend → SES → SMTP, and skips any that isn't configured. None of them is needed to start the app, and none is used with SPRING_PROFILES_ACTIVE=mock-email.

Variable Example Description
RESEND_API_KEY re_xxxxxxxxxxxx Resend API key (primary sender)
MAIL_HOST smtp.resend.com SMTP host
MAIL_PORT 587 SMTP port (STARTTLS)
MAIL_USERNAME resend SMTP username
MAIL_PASSWORD re_xxxxxxxxxxxx SMTP password / API key

AWS

All optional. Without them the app starts, SES is skipped, and image uploads return an error.

Variable Example Description
AWS_REGION eu-north-1 AWS region for SES and S3 (default us-east-1)
AWS_ACCESS_KEY_ID AKIA… IAM access key. Leave both keys unset to use the AWS SDK's default credentials chain (for example an IAM role)
AWS_SECRET_ACCESS_KEY … IAM secret key
AWS_S3_BUCKET mailengine-assets S3 bucket for template images and uploads
SES_SNS_TOPIC_ARNS arn:aws:sns:eu-north-1:123456789012:ses-events Comma-separated SNS topics allowed to post to /webhooks/ses. Set it: unset, any SNS topic is accepted (a warning is logged at startup)

Optional

Variable Example Description
CORS_ALLOWED_ORIGINS https://app.yourdomain.com Comma-separated browser origins allowed to call the API. Default * (any origin)
GEOIP_DATABASE_PATH /data/GeoLite2-City.mmdb MaxMind GeoLite2 / GeoIP2 City (or Country) database file for IP → country/city on tracking events, looked up offline. Without it, events are stored without location. See IP geolocation
SEND_RATE_PER_SECOND 14 Emails per second the send worker may send. Match your provider's limit (SES: 14 by default, 1 in the sandbox). 0 turns the cap off. Default 14
LOGIN_RATE_LIMIT_PER_MINUTE 20 Login attempts per client IP per minute (429 beyond). Default 20
ACCOUNT_EMAIL_RATE_LIMIT_PER_HOUR 10 Forgot-password, reset-password and verify-email requests per client IP per hour. Default 10
ANALYTICS_CACHE_TTL 60s How long analytics answers are cached. Default 60s
SPRING_PROFILES_ACTIVE mock-email Set to mock-email to log emails to console instead of sending them
LOGGING_LEVEL_<PACKAGE> LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_SECURITY=DEBUG Raise logging for one package while debugging. Everything logs at INFO by default

Database

Schema is managed entirely by Flyway. Never edit the database by hand — add a new migration file instead.

Migration files

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.

Adding a migration

Create the next file in sequence:

src/main/resources/db/migration/V2__your_description.sql

Flyway applies it automatically on the next startup. Never modify an already-applied migration — Flyway checksums every file and will refuse to start if a previously applied file changes.

Key tables

Table Purpose
users Accounts with roles (admin / editor / viewer), lockout state, mustChangePwd
campaigns Campaign metadata + aggregate stat counters
email_queue One row per recipient per campaign; drives the send worker
tracking_events Every open / click / unsubscribe / bounce / complaint event
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, 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)
templates HTML email templates with optional JSON visual-editor state
recipient_list_members Which recipients are in which list
campaign_recipient_lists Which lists a campaign sends to
read_duration_events Read-time checkpoints for opened emails
password_reset_tokens, email_verification_tokens One-time tokens, stored as SHA-256 hashes (the token itself is only in the email)

Deleting a user keeps the templates and campaigns they created (created_by becomes empty). A template or list that a campaign uses can't be deleted: the API answers 409 and says how many campaigns use it.


Running the App

Development

./gradlew bootRun

Spring DevTools is on the classpath — the app will restart automatically when you recompile.

Build a JAR

./gradlew bootJar
java -jar build/libs/mailengine-0.0.1-SNAPSHOT.jar

Docker

The Dockerfile builds the app with JDK 21 and runs it on a JRE 21 image as a non-root user. Gradle and all dependencies are downloaded in their own layer (./gradlew downloadDependencies) before the source is copied in, so after a code change only the compile step runs. CI keeps that layer in its build cache, so it doesn't download from Maven Central on every run.

docker build -t mailengine .
docker run -d --name mailengine -p 8080:8080 --env-file .env --stop-timeout 35 mailengine

For IP geolocation, mount the MaxMind file too (see IP geolocation). In the env file, DB_HOST must be reachable from inside the container: use host.docker.internal for a database on your machine (Docker Desktop), or the database container's name when both are on the same Docker network. --stop-timeout 35 gives running imports time to finish on shutdown (see Deployment).

See Testing for the test suites.


Testing

Tests use JUnit 6, Mockito and AssertJ. There are three suites:

Command What runs Needs
./gradlew test Unit and web-layer tests: auth, JWT, the full role × route permission matrix, user management, and import edge cases Nothing
./gradlew integrationTest Whole-app tests against a real PostgreSQL: campaign sending, the email worker (pause, retries, completion, crashed workers), scheduled sends, SES webhooks, error codes, the mock-email profile Docker
./gradlew scaleTest Import scale, concurrency, shutdown and recovery tests against a real PostgreSQL Docker
./gradlew test

# Scale tests: choose row counts and heap size
./gradlew scaleTest -PimportRows=1000,50000 -PscaleHeap=512m

Integration tests are tagged integration, and scale tests are tagged scale. Both are excluded from ./gradlew test. Integration tests run with the JVM in a non-UTC time zone (Africa/Lagos) on purpose, to catch code that mixes UTC timestamps with the database's local NOW().

Scale tests start postgres:16-alpine with Testcontainers, upload generated CSV/XLSX files through the real endpoint, and print each measurement as a SCALE | line. The same lines are appended to build/scale-results.txt.

Notes:

  • MailengineApplicationTests.contextLoads starts the whole app against PostgreSQL in Docker, so it runs with ./gradlew integrationTest and doesn't need a local .env.
  • CI (.github/workflows/ci.yml) runs all three suites and builds the Docker image on every pull request and every push to main.
  • scaleTest turns off Testcontainers' Ryuk cleanup container, because some Docker Desktop setups can't pull it. The tests stop their own container when the JVM exits.

Where things live:

Path Covers
security/SecurityWebTest Every role against every API route, token edge cases, forced password change, malformed input
security/JwtServiceTest, security/JwtAuthFilterTest Token validation and the authentication filter
service/AuthServiceTest, service/UserServiceTest Login and lockout, password flows, admin-only user management
service/FileUploadServiceTest Import edge cases: headers and BOM, invalid rows, duplicates, Excel, failure paths
importscale/* Throughput, memory, bounded import pool, email isolation, restart recovery
integration/* Campaign pipeline end to end on PostgreSQL, column mapping, user/template/list deletion rules, upload and test-send validation; the mock-email profile starts
worker/*, service/SesEventServiceTest, util/SnsMessageVerifierTest Worker decisions, scheduled sends, bounce/complaint handling, SNS signature checks

Mock Email Mode

To develop without real email infrastructure, set:

SPRING_PROFILES_ACTIVE=mock-email

This activates MockEmailSender, which logs every outbound email to the console instead of sending it: recipient, sender, subject, the email's readable text (tags stripped, up to 1,000 characters) and its links. That is enough to use invitations and password resets locally: the invite's temporary password and the reset link are right there in the log. It returns a synthetic mock-{UUID} message ID. No external service is called.

Never use this profile where real people get emails: their temporary passwords and reset links end up in the log.

All other functionality (queueing, tracking, analytics) works identically in this mode.


Roles & Permissions

Every user has one role. Spring Security enforces these rules in SecurityConfig:

Route viewer editor admin
GET /api/** (read anything) ✅ ✅ ✅
POST/PUT/PATCH/DELETE /api/** (create, edit, send, delete) ❌ 403 ✅ ✅
/api/users/** (user management) ❌ 403 ❌ 403 ✅
  • No token, or an invalid or expired one: 401.
  • Public, no token needed: /api/auth/** (except change-password), /track/**, /webhooks/**, Swagger, /ready, and GET /api/recipient-lists/template/**.
  • Forced password change: a user with mustChangePwd (newly invited, or reset by an admin) can only call POST /api/auth/change-password. Everything else returns 403 until they change it.
  • Temporary passwords (invites and admin resets) are 16 random characters and expire: after 7 days for an invite, 24 hours for an admin reset. Login then refuses them with 401 "Temporary password has expired"; an admin issues a new one with POST /api/users/{id}/reset-password. The seeded admin's first password doesn't expire.
  • Role changes take effect on the next request, because the user and their role are loaded from the database for every request, not taken from the token.
  • Admins can't change their own role or delete themselves, so at least one admin always remains.
  • UserService repeats the admin check as a second line of defence.

Account protections:

  • Emails are matched without regard to case (Admin@x.com is the same account as admin@x.com).
  • After 5 wrong passwords the account is locked for 15 minutes. Once the lock expires, the user gets a fresh 5 attempts.
  • Rate limits per client IP (Bucket4j): 20 login attempts a minute, and 10 forgot-password / reset-password / verify-email requests an hour (429 with Retry-After beyond). On top, at most 3 reset emails per address per hour, however many clients ask, so nobody can flood an inbox. Limits are kept in memory, per app instance.
  • "Please verify your email" is only shown after a correct password, so it can't be used to discover which addresses have accounts.
  • Password reset and email verification links work once, and only their SHA-256 hash is stored, so someone who can read the database can't use them. Reset links expire after 1 hour.
  • Self-registration is disabled (POST /api/auth/register returns 400): admins invite users.
  • Passwords must be 8–72 characters. BCrypt ignores anything after 72 bytes, so longer passwords are rejected rather than silently cut short.

API Reference

Full interactive docs are available at http://localhost:8080/swagger-ui.html once the app is running. All endpoints (except those listed as public) require:

Authorization: Bearer <jwt-token>

Auth — /api/auth

Method Path Auth Description
POST /login — Returns JWT token + mustChangePassword flag
POST /change-password JWT (any role) Changes password (new one must differ from the current one); clears mustChangePassword
POST /forgot-password — Sends password reset email (always 200 — no user enumeration)
POST /reset-password — Consumes single-use token, sets new password
GET/POST /verify-email — Verifies email address via one-time token
POST /register — Disabled: always 400 (users are invited by an admin)

Users — /api/users (admin only — every endpoint)

Method Path Description
GET / List all users
POST /invite Invite a new user (temp password emailed, mustChangePwd = true)
PUT /{id}/role Update a user's role (cannot change own role)
DELETE /{id} Delete a user (cannot delete self)
POST /{id}/reset-password Admin-generates a new temp password for a user

Campaigns — /api/campaigns

Method Path Description
GET / Paginated list; optional ?status= filter
POST / Create a campaign (starts as DRAFT)
GET /{id} Get campaign details + counters
PUT /{id} Update (DRAFT only)
DELETE /{id} Delete (DRAFT only)
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/skipped counts
POST /{id}/pause Pause an in-progress send
POST /{id}/resume Resume a paused send

Recipient Lists — /api/recipient-lists

Method Path Description
GET / All lists
POST / Create a list
PUT /{id} Rename / update description
DELETE /{id} Delete a list and its upload history (409 if a campaign uses it)
GET /{id}/export Download all recipients as CSV
GET /{listId}/recipients Paginated recipients with optional ?search=
POST /{listId}/upload Upload a CSV, XLSX or XLS file (202, async — returns uploadId; 503 if the import queue is full)
GET /template/csv Download the CSV import template
GET /template/xlsx Download the XLSX import template

Uploads — /api/uploads

Method Path Description
GET /{uploadId}/status Poll file import progress and stats
POST /{uploadId}/map Import an upload whose headers didn't match, using a column mapping (see File Import)

Templates — /api/templates

Method Path Description
GET / Paginated list; optional ?category= filter
POST / Create a template
GET /{id} Get template
PUT /{id} Update template
DELETE /{id} Delete template (409 if a campaign uses it)
POST /{id}/duplicate Clone template (appends " (Copy)")
POST /upload-html Read an .html/.htm file (UTF-8), returns the HTML string; other files get 400

Image Upload — /api/upload

Method Path Description
POST /image Upload an image to S3, returns {url}

Analytics — /api/analytics

Method Path Description
GET /campaigns/{id}/overview Open/click/bounce/unsub rates + totals
GET /campaigns/{id}/timeline Hourly engagement curve
GET /campaigns/{id}/links Per-link click count and unique click rate
GET /campaigns/{id}/devices Breakdown by device type, OS, email client
GET /campaigns/{id}/geography Breakdown by country and city
GET /engagement-scores All recipient engagement scores
POST /engagement-scores/refresh Manually trigger score recalculation

Tracking — /track (public, no auth)

Method Path Description
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} 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)

Method Path Description
POST /ses Receives SNS notifications for delivery, bounce, complaint events

Core Concepts

Campaign Send Pipeline

When you call POST /api/campaigns/{id}/send, this is what happens:

1. Validate
   └─ Campaign must be DRAFT or SCHEDULED
   └─ Campaign must have a template assigned

2. Collect eligible recipients
   └─ Join: campaign → recipient lists → list members → recipients
   └─ Filter: recipient.status = ACTIVE only
   └─ Exclude: any email present in suppression_list
   └─ Deduplicate: by email address across lists

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)
   └─ Inject unsubscribe:  replaces {{unsubscribe_url}}  or appends link before </body>
   └─ Inject open pixel:   <img src="/track/open/{pixelToken}?cb={ts}" />  before </body>

4. Queue emails
   └─ Insert one email_queue row per recipient (status = PENDING)
   └─ Each row gets three unique UUID tokens: pixelToken, clickToken, unsubToken

5. Update state
   └─ campaign.status = SENDING
   └─ campaign.totalRecipients = count
   └─ Create campaign_job (status = PROCESSING, totalEmails = count)

The background worker (EmailSenderWorker) then picks up from the queue:

Every 3 seconds (at most app.sending.rate-per-second emails per second, default 14):
  SELECT * FROM email_queue
  WHERE status = 'pending'
  AND (locked_until IS NULL OR locked_until < NOW())
  LIMIT 20                        ← app.sending.batch-size
  FOR UPDATE SKIP LOCKED          ← safe for multiple concurrent workers

  For each row:
    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
              attempts < 3: status = PENDING, retry later
                            (2 min after the 1st failure, 4 min after the 2nd)
              attempts = 3: status = FAILED

  Update campaign_job counters atomically (SQL INCREMENT)
  If 0 pending rows remain → job.status = COMPLETED

Email Tracking

Every email contains three invisible tracking mechanisms:

Open tracking — a 1×1 transparent PNG pixel:

<img src="{APP_BASE_URL}/track/open/{pixelToken}?cb=1234567890" width="1" height="1" />

When the email client loads this image, TrackingService.handleOpen() fires:

  • Resolves campaign + recipient from pixelToken
  • Extracts IP from X-Forwarded-For → looks up country/city in the MaxMind database (offline)
  • Parses User-Agent via Yauaa for device type, OS, email client
  • Sets isAppleProxy = true when the open comes from Apple's network, 17.0.0.0/8. Apple Mail Privacy Protection pre-fetches every image through Apple's proxies, so these opens don't mean a person read the email. The flag is stored on each open event; analytics doesn't use it yet.
  • Saves a TrackingEvent(type=open)
  • Returns the 67-byte PNG so the email renders normally

Click tracking — every link is rewritten:

<!-- Original -->
<a href="https://yoursite.com/pricing">See pricing</a>

<!-- After personalisation -->
<a href="{APP_BASE_URL}/track/click/{clickToken}?t=aHR0cHM6Ly95b3Vyc2l0ZS5jb20vcHJpY2luZw==">See pricing</a>

The ?t= value is the original URL base64url-encoded. On click: log event → 302 redirect → recipient lands on original URL. Transparent to the recipient.

Only links that are really in that recipient's email are followed: an unknown token, or a ?t= that isn't in the email, gets 404. Otherwise the endpoint would be an open redirect (anyone could make a link on your domain that lands on a phishing page) and fake clicks could be recorded.

IP geolocation

Country and city come from a MaxMind database file read locally: no network call per event, no per-lookup cost. Create a free MaxMind account, download GeoLite2 City (GeoLite2-City.mmdb), and point GEOIP_DATABASE_PATH at it. MaxMind updates the database regularly; their geoipupdate tool fetches new versions, and the app loads the file at startup. A Country database works too (country only). The file is not in the repository (MaxMind's licence doesn't allow redistributing it). In Docker, mount it: -v /path/GeoLite2-City.mmdb:/data/GeoLite2-City.mmdb:ro -e GEOIP_DATABASE_PATH=/data/GeoLite2-City.mmdb.

Unsubscribe tracking — a link injected near the bottom of every email:

{APP_BASE_URL}/track/unsubscribe/{unsubToken}

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.

Webhook Events (AWS SNS)

AWS SES can publish delivery events to an SNS topic which forwards them as HTTP POSTs to /webhooks/ses. This is the only way to receive bounce and complaint notifications.

Setup (one-time in AWS console):

  1. Create an SNS topic
  2. Add an HTTP subscription pointing to {APP_BASE_URL}/webhooks/ses
  3. Set the SNS topic as the SES notification destination for Bounces and Complaints
  4. Set SES_SNS_TOPIC_ARNS to the topic's ARN

On each webhook:

  • The controller verifies the AWS SNS signature to prevent spoofing
  • Messages from a topic not in SES_SNS_TOPIC_ARNS get 403: a valid signature proves only that the message came from SNS, not from your topic
  • Events are correlated to the right campaign + recipient via email_queue.message_id (the SES message ID stored when each email is sent)
  • Bounce → recipient.status = BOUNCED, add to suppression_list
  • Complaint → recipient.status = COMPLAINED, add to suppression_list
  • Delivery → increment campaign.totalDelivered

Once an email is in the suppression list it can never be imported or sent to again.

Analytics

AnalyticsService aggregates tracking_events rows on demand. Each answer is cached per campaign in memory (Caffeine) for ANALYTICS_CACHE_TTL (default 60 s), so a dashboard refreshing every few seconds doesn't repeat the heavy queries; numbers can lag that much during a send. Engagement scores are cached too, and cleared whenever they are recalculated.

Endpoint How it's calculated
Overview rates openRate = opens / delivered × 100 (rounded to 2 dp). delivered comes from SES delivery events, or sent − bounced without them
Timeline DATE_TRUNC('hour', created_at) buckets, one row per hour
Link performance Group by link_url, count total + COUNT(DISTINCT recipient_id) for uniques
Device breakdown Group by device_type, count opens and clicks, calculate % of total
Geography Group by geo_country, geo_city, count opens and clicks

File Import

POST /api/recipient-lists/{listId}/upload accepts a CSV, XLSX or XLS file (max 10 MB). It answers immediately with 202 and an uploadId, and the import runs in the background. Poll GET /api/uploads/{uploadId}/status until the status is completed or failed, then read the counts (total, imported, skipped, duplicates).

Formats

  • CSV: read as UTF-8. The byte-order mark Excel writes in "CSV UTF-8" files is ignored.
  • XLSX: read row by row (POI SAX streaming), so memory stays flat however many rows there are. Formula cells use their saved result.
  • XLS: legacy format, at most 65,536 rows. Formulas are evaluated.
  • Columns: email, first_name and last_name are required. Case and order don't matter, and extra columns are ignored.

Column mapping. If the headers don't include those three, nothing is imported yet: the upload ends failed with needsMapping: true, and the status lists the file's columns with a preview of the first row's values. The file is kept (for up to a day) until it is mapped:

POST /api/uploads/{uploadId}/map
{"mapping": {"E-mail": "email", "Given Name": "first_name", "Surname": "last_name", "Notes": "ignore"}}

Keys are the file's headers (any case) and values the fields; the other direction ({"email": "E-mail", ...}) works too. The import then runs with the mapping and the response has the real counts (imported, skipped, duplicates). A mapping naming a column that isn't in the file, or leaving a field unmapped, gets 400 and the upload can be mapped again; an upload that is already imported gets 409.

Per row, each row is handled on its own, so one bad row never fails the file:

1. Skip if the email is blank, isn't a valid address, or any value is over 255 chars → skipped++
2. Normalise the email (trim + lowercase)
3. Skip if the email is in suppression_list                                          → skipped++
4. If the recipient already exists:
   a. status UNSUBSCRIBED or BOUNCED → skipped++
   b. not yet in this list           → add membership → imported++
   c. already in this list           → duplicates++
5. Otherwise create the recipient and add it to the list                             → imported++
   (if a parallel import created the same address a moment earlier, reuse that one)
6. Any unexpected error on this row                                                  → skipped++, carry on

After every import, finished or failed, recipient_lists.recipient_count is recomputed from the actual memberships.

Background processing

Imports run on a dedicated thread pool, separate from the one that sends transactional emails, so large imports never delay password-reset or invitation emails.

Property Default Meaning
app.import.threads 4 Imports processed at the same time
app.import.queue-capacity 10 Uploads that may wait. When full, new uploads get 503 and are marked failed

Each waiting upload holds its file (up to 10 MB) in memory, so queue-capacity also limits memory use. POST /api/uploads/{id}/map runs on the same pool and answers once the import is done (503 if the pool is full).

Restarts: on shutdown, Spring waits up to 30 s (spring.lifecycle.timeout-per-shutdown-phase) for running imports. Anything still unfinished can't record its result, so on the next startup ImportRecovery marks every upload left in processing as failed. Users can then simply upload again. This assumes a single app instance.

Measured limits (Docker PostgreSQL, 512 MB heap; reproduce with ./gradlew scaleTest):

File Rows Time Peak heap
CSV, 2.3 MB 50,000 ~105 s ~196 MB
CSV, 9.4 MB (near the 10 MB cap) 200,000 ~7 min ~330 MB
XLSX, 3.7 MB 200,000 ~7 min ~295 MB

Throughput is about 500 rows/second, which works out to 5 database statements per row.

Import templates (with the correct column headers) are downloadable at:

  • GET /api/recipient-lists/template/csv
  • GET /api/recipient-lists/template/xlsx

Engagement Scoring

EngagementScoreService runs a scheduled job every night at 02:00 and recalculates a score (0–100) for every recipient using an RFM-style model:

recencyScore   = (1 − min(daysSinceLastActivity, 90) / 90) × 40   (max 40 pts; last click, else last open)
frequencyScore = min(opened / sent, 1)                × 30   (max 30 pts)
clickScore     = min(clicked / opened, 1)             × 30   (max 30 pts)

total = recencyScore + frequencyScore + clickScore

Categories:
  ≥ 70  → "high"
  ≥ 40  → "medium"
  > 0   → "low"
  = 0   → "inactive"

Scores can also be refreshed manually via POST /api/analytics/engagement-scores/refresh.


Adding a New Feature

The typical pattern for adding a new resource (e.g. "Tags"):

1. Database migration

-- src/main/resources/db/migration/V2__create_tags.sql  (the next free number)
CREATE TABLE tags (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);

2. Entity

// src/.../entity/Tag.java
@Entity
@Table(name = "tags")
@Data @NoArgsConstructor
public class Tag {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private Instant createdAt;
}

3. Repository

// src/.../repository/TagRepository.java
public interface TagRepository extends JpaRepository<Tag, Long> {
    Optional<Tag> findByName(String name);
}

4. DTOs

// dto/request/CreateTagRequest.java
public record CreateTagRequest(@NotBlank String name) {}

// dto/response/TagResponse.java
public record TagResponse(Long id, String name, Instant createdAt) {}

5. Service

@Service
@RequiredArgsConstructor
public class TagService {
    private final TagRepository tagRepository;

    @Transactional(readOnly = true)
    public List<TagResponse> getTags() { ... }

    @Transactional
    public TagResponse createTag(CreateTagRequest req) { ... }
}

6. Controller

@RestController
@RequestMapping("/api/tags")
@RequiredArgsConstructor
public class TagController {
    private final TagService tagService;

    @GetMapping
    public ResponseEntity<List<TagResponse>> getTags() { ... }

    @PostMapping
    public ResponseEntity<TagResponse> createTag(@Valid @RequestBody CreateTagRequest req) { ... }
}

7. Exception handling

Use the existing custom exceptions — no new classes needed in most cases:

  • ResourceNotFoundException → 404
  • ConflictException → 409
  • BadRequestException → 400
  • UnauthorizedException → 401
  • AccessDeniedException (Spring Security) → 403

GlobalExceptionHandler catches them automatically. It also maps common client mistakes to 4xx instead of 500:

Cause Status
Malformed JSON, unknown enum value, non-numeric id, missing request parameter 400
Unknown route 404
Wrong HTTP method 405
Database constraint violation (prefer checking first and throwing ConflictException with a reason) 409

To get the current user in a service, use SecurityUtils.currentUser(). It returns 401 instead of crashing when nobody is logged in.


Deployment

Required infrastructure

Service Purpose
PostgreSQL instance Primary database
Resend account Email sending (recommended primary)
AWS SES Email sending fallback + bounce/complaint webhooks
AWS S3 Template image and file storage
AWS SNS Forwards SES events to /webhooks/ses
MaxMind GeoLite2 / GeoIP2 database file IP geolocation on tracking events

Key configuration for production

  1. APP_BASE_URL — Set to your public domain (https://api.yourdomain.com). This URL is baked into every tracking link inside sent emails. If it changes after sending, existing tracking links break.

  2. JWT_SECRET — Must be at minimum 32 characters. Rotate it only during a maintenance window (all existing tokens become invalid).

  3. CORS — any origin may call the API by default. Set CORS_ALLOWED_ORIGINS to your frontend's domain(s) in production. Browsers never send cookies or other credentials: auth is the Authorization: Bearer header.

  4. Logging levels — everything logs at INFO. Raise a package with LOGGING_LEVEL_<PACKAGE>=DEBUG only while debugging: Spring's DEBUG output includes request details.

  5. Imports and restarts: give the app a stop grace period of at least 30 s (for example docker run --stop-timeout 35, or docker stop -t 35) so running imports can finish. Docker's default is 10 s. Anything cut off is marked failed at the next startup. Tune app.import.threads / app.import.queue-capacity to your memory and database capacity.

  6. Single instance: startup import recovery assumes one app instance. If you run several against the same database, revisit ImportRecovery first.

  7. server.forward-headers-strategy: native — Already configured. Tracking records the client IP that Tomcat works out from X-Forwarded-For, and Tomcat only trusts that header when it comes from an internal proxy address (private ranges such as 10.x, 172.16–31.x, 192.168.x and localhost). If your reverse proxy or load balancer reaches the app from a public IP, every open and click is recorded with the proxy's IP: add the proxy's address to server.tomcat.remoteip.internal-proxies (a regex).

  8. Never run with SPRING_PROFILES_ACTIVE=mock-email in production: emails aren't sent, and temporary passwords and reset links are written to the log.

  9. Container image: build it with the Dockerfile (see Docker). It exposes port 8080 and runs as a non-root user.

Environment variable checklist for production

DB_HOST, DB_PORT, DB_NAME, DB_USERNAME, DB_PASSWORD
JWT_SECRET, JWT_EXPIRATION
APP_BASE_URL, AWS_FROM_EMAIL
CORS_ALLOWED_ORIGINS
RESEND_API_KEY  (and/or SES via AWS_*, and/or MAIL_HOST/MAIL_PORT/MAIL_USERNAME/MAIL_PASSWORD for SMTP)
AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY (or an IAM role), AWS_S3_BUCKET
GEOIP_DATABASE_PATH (mount the .mmdb file)
SEND_RATE_PER_SECOND (your provider's limit)

Health check endpoint

GET /ready → 200 "OK"

Use this for load balancer and container orchestration health checks.

About

A self-hosted email marketing platform for sending bulk campaigns, tracking engagement, and analyzing results. Built with Spring Boot 3.5 / Java 21 / PostgreSQL.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages