When I started testing email sending in my Spring Boot app with Mailpit and Testcontainers, I ran into a frustrating problem: sending mail locally to localhost often hung for many seconds before failing.

The root cause was slow or failing DNS resolution of my local hostname during the JavaMail SMTP handshake. Once I understood what was happening, the fix was simple. Even better, this is now properly solved by the dedicated Testcontainers integration I created:
👉 https://github.com/martinellich/testcontainers-mailpit

If you use this module together with the setup described in my article
https://martinelli.ch/testing-emails-with-testcontainers-and-mailpit/
you will not run into these timeout problems anymore.

Why the Timeouts Happen

When JavaMail connects to an SMTP server, it starts with:

EHLO <hostname>

If you do not explicitly configure

mail.smtp.localhost=localhost

JavaMail calls:

InetAddress.getLocalHost()

This often triggers a reverse DNS lookup of your machine’s hostname. In local environments this can be slow or misconfigured. Especially in:

  • Docker setups
  • CI environments
  • macOS with incomplete /etc/hosts
  • VPN environments

If hostname resolution blocks, the EHLO handshake blocks. That is the timeout you see.

A second lookup can happen when JavaMail builds the envelope sender (MAIL FROM). If mail.from is not set, it constructs something like:

<username>@<local hostname>

Which again may require hostname resolution.

Same root cause. Same delay.

Why Explicit Configuration Fixes It

Setting

spring.mail.properties.mail.smtp.localhost=localhost
spring.mail.properties.mail.from=test@example.com

prevents JavaMail from trying to resolve the local hostname.

No reverse DNS lookup.
No blocking handshake.
No mysterious timeout.

The Better Solution: testcontainers-mailpit

Instead of manually wiring Mailpit and remembering all SMTP edge cases, I created a small integration:

https://github.com/martinellich/testcontainers-mailpit

This module provides:

  • MailpitContainer for Testcontainers
  • MailpitClient to inspect received messages
  • Optional AssertJ support
  • Smooth integration with Spring Boot 3.1+ via @ServiceConnection

Most importantly, the setup shown in that repository and in my blog post already avoids the DNS lookup pitfall. If you follow that integration, the timeout issue is effectively solved.

Since using this module, my email tests:

  • Run in milliseconds
  • Are stable locally and in CI
  • Do not randomly hang
  • Work reliably with Testcontainers

The real lesson here is simple: the problem was never Mailpit. It was implicit DNS resolution during the SMTP handshake.

Sometimes performance issues are not about infrastructure. They are about one hidden hostname lookup.

And once you remove it, everything becomes fast again.