Testing Java mail services with GreenMail and SMTP

Integration tests for Java mail services should verify the boundary where application code hands a message to an SMTP server. A test that only asserts a MimeMessage object looks correct can miss bad configuration, incorrect recipients and failures in the mail gateway. GreenMail supplies a lightweight SMTP server, allowing the production mail component to complete a real socket conversation without contacting an external provider.

Using GreenMail with Jakarta Mail or legacy JavaMail turns sending into an observable event: the test starts a server, invokes the service, waits for delivery and inspects what arrived. This is especially valuable to teams in Sydney and Melbourne that release continuously, because the check can run in every build without sending customer email or depending on a public sandbox.

Choosing the correct test boundary

First, define the boundary being tested. GreenMail is appropriate when the behaviour under examination includes SMTP configuration, connection handling, recipient selection, MIME construction and the handoff to a mail gateway. It is less useful for testing a formatter in isolation, because that belongs in a fast unit test with no socket involved.

The boundary also determines which provider features need separate tests. Where the architecture includes managed email, compare GreenMail with delivery behaviour offered by services such as Mailgun, SendGrid or Australian provider SMTP2GO. Organisations such as Brightnewt IT services can provide a wider architectural perspective, while the automated suite can remain independent of external infrastructure.

GreenMail cannot reproduce production DNS, SPF, DKIM, DMARC, reputation, throttling, bounce handling or delivery-provider webhooks. Keep those guarantees in provider sandbox tests or a controlled staging environment. GreenMail should prove the application’s SMTP behaviour reliably and quickly, not pretend to be a complete email-delivery platform.

Building an isolated GreenMail fixture

Use the JUnit 5 module and pin a compatible GreenMail version in the project’s dependency management. The version can remain a property so every module uses the same release:

<dependency>
  <groupId>com.icegreen</groupId>
  <artifactId>greenmail-junit5</artifactId>
  <version>${greenmail.version}</version>
  <scope>test</scope>
</dependency>

A GreenMail extension can manage the server lifecycle for each test. Binding to a dynamically assigned loopback port prevents collisions when JUnit executes tests in parallel:

@RegisterExtension
static GreenMailExtension greenMail =
    new GreenMailExtension(new ServerSetup(0, "127.0.0.1"));

Read the actual bound port from the started GreenMail instance and pass it to the application under test. Avoid fixed ports such as 25, 465 or 587, which may be occupied or require elevated privileges. Loopback binding also ensures that a misconfigured test cannot accidentally reach a real mail service.

Keep one mailbox state per test. Reset received messages between assertions or test cases, and verify that the fixture is stopped even when a test fails. This isolation prevents one message from contaminating another and keeps parallel execution predictable.

Connecting JavaMail to the test server

Inject the SMTP host and port into the component that creates the Session. A typical plain-SMTP configuration for GreenMail looks like this:

Properties properties = new Properties();
properties.setProperty("mail.smtp.host", "127.0.0.1");
properties.setProperty("mail.smtp.port", Integer.toString(smtpPort));
properties.setProperty("mail.smtp.auth", "false");
properties.setProperty("mail.smtp.starttls.enable", "false");
properties.setProperty("mail.smtp.connectiontimeout", "3000");
properties.setProperty("mail.smtp.timeout", "3000");
properties.setProperty("mail.smtp.writetimeout", "3000");

Session session = Session.getInstance(properties);

These values should override the application’s normal configuration only within the test environment. Production defaults might point to an Australian provider, require authentication or enable TLS, so silently reusing those settings would either fail or create an unwanted outbound connection.

The test should invoke the application’s actual mail service rather than constructing and sending a separate message. If the service accepts an envelope recipient, pass it explicitly:

Transport.send(message, "customer@example.net");

Using the same gateway under test confirms that its configuration, recipient handling and exception translation work as expected.

Verifying content and delivery behavior

After delivery, inspect the received message rather than the object originally passed to the sender. Assert the recipient set, subject, body, content type and important headers. For multipart mail, check each alternative and attachment by filename, MIME type and content so a placeholder body cannot satisfy the test accidentally.

Distinguish header recipients from envelope recipients. A message may contain a visible To header while the SMTP command sends it to a different mailbox. Tests should assert both when the application supports multiple recipients or BCC handling, because leaked recipients are a common production defect.

Use Australian-safe fixtures such as orders@example.com.au, but make sure recipient data is synthetic and clearly non-deliverable. GreenMail does not enforce Australian marketing-email rules. Any campaign workflow must still implement consent, identification and unsubscribe requirements under the Spam Act 2003; those controls need their own focused tests.

Making asynchronous tests deterministic

Polling with a deadline is preferable to Thread.sleep. GreenMail can wait until the expected number of messages arrives, after which the test retrieves and inspects them:

assertThat(greenMail.waitForIncomingEmail(5_000, 1)).isTrue();

MimeMessage[] received = greenMail.getReceivedMessages();
assertThat(received).hasSize(1);

Choose a timeout that reflects the tested component rather than an arbitrary long pause. If the application publishes work to a queue, remember that reaching GreenMail proves only the SMTP handoff succeeded. Wait separately for the queue worker, database update, webhook or other downstream side effect before asserting the complete workflow.

Clock and timezone assumptions deserve particular attention. Brisbane observes Australian Central Standard Time and Perth Australian Western Standard Time, while Sydney and Melbourne experience daylight-saving changes. Store and compare instants, but also assert the RFC-compliant date header and intended Australian local representation where that is part of the contract. Inject a fixed clock when a test needs an exact timestamp.

Running the suite in CI and team workflows

GreenMail is well suited to continuous integration because it starts quickly, requires no container and makes no public network call. Run it on the same operating-system matrix as the application, and ensure the SMTP endpoint is overridden in every test profile. A CI log should clearly identify the bound port and any timeout, making failures easier to diagnose across Linux, macOS and Windows workers.

The same isolation principle used for JUnit temporary folders applies here: give every worker a disposable server and deterministic inputs, then tear it down. Avoid sharing a class-wide server when tests can execute concurrently, because message counts and asynchronous callbacks become order-dependent.

Treat flakiness as a defect in the test design. Replace fixed sleeps with observable conditions, remove reliance on the host’s default timezone and locale, and use unique data for each test. Provider sandbox checks can run separately in a later pipeline stage, while GreenMail protects the fast feedback required for every commit.

A durable verification checklist

The most reliable suites make their assumptions visible and keep each responsibility in the appropriate layer:

These practices produce fast, repeatable feedback while keeping customer data and external systems outside the build.

The principle to remember is simple: make the SMTP boundary deterministic, assert observable behaviour and reserve external-delivery guarantees for tests designed around the actual provider.