📮 In short: connecting email sending in Spring Boot can be done in 10 minutes. Making sure emails are not lost, duplicated, do not block the user, and do not depend on a single provider is a separate task. I will cover 8 solutions with examples from my blog: what to do, why exactly this way, and what it gives in practice.
📬 Haven't chosen a provider yet? Start with a review of 7 services for sending emails: prices, limits, and when to choose which and a comparison of Resend vs SendGrid.
⚡ The main points in 30 seconds
- ✅ SMTP — when independence from the provider is important, HTTP API — when idempotency, tags, and batch sending are needed.
- ✅ Business logic should not know about the provider: interface + implementations, switched via
@ConditionalOnProperty.
- ✅ Email templates on your side (Thymeleaf), so switching to another provider doesn't mean rewriting templates.
- ✅ Email sending — asynchronously and after transaction commit, not within it.
- ✅ Retry only temporary errors (429, 5xx) and with an idempotency key.
📑 Table of Contents:
⚖️ SMTP or HTTP API
Most services (Resend, SendGrid, Mailgun, Postmark) offer both methods. The choice between them is a choice between flexibility and features.
|
SMTP (JavaMailSender) |
HTTP API (SDK) |
| Provider change |
Change host and password in config |
New implementation in code |
| Dependencies |
spring-boot-starter-mail |
Provider-specific SDK |
| Idempotency, tags, batch |
Partially, via custom headers |
Yes, out-of-the-box |
| Response |
"Accepted by server" |
Email ID, which can be further processed |
| When to choose |
Simple project, few providers, legacy |
Bulk sending, reliable retries, webhooks |
In my blog, I use Resend's HTTP API via the Java SDK: I need email IDs and delivery analytics. But for a small project, SMTP is a perfectly fine choice.
📨 SMTP via JavaMailSender
What it is. The standard Java way to send mail: Spring Boot automatically configures JavaMailSender based on spring.mail.* properties.
Why this way. SMTP is a universal protocol, supported by any provider. The sending code knows nothing about Resend or SendGrid.
What this gives in practice. Switching from Resend to SendGrid means changing three lines of configuration, without a single line of Java code:
# Resend
spring.mail.host=smtp.resend.com
spring.mail.port=587
spring.mail.username=resend
spring.mail.password=${RESEND_API_KEY}
# SendGrid: host=smtp.sendgrid.net, username=apikey, password=${SENDGRID_API_KEY}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=10000
spring.mail.properties.mail.smtp.writetimeout=10000
Note two details. The login is a literal string: resend for Resend and apikey for SendGrid, and the API key itself goes into the password. And timeouts: by default, JavaMail waits indefinitely for the server's response. If the SMTP server hangs, your application's thread will hang with it.
Sending itself:
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");
helper.setFrom("WebCraft <[email protected]>");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(html, true); // true = HTML
mailSender.send(message);
🔌 HTTP API via SDK
What it is. Sending via the provider's REST API using its official library.
Why so. The API has features that SMTP lacks: it returns an email ID, supports tags for analytics, scheduled sending, batching (up to 100 emails per request in Resend), and idempotency keys. More on these in the retries section.
What this means in practice. More control and more reliable retries, but the code is tied to a single provider. Therefore, the SDK should be hidden behind an interface – that's what the next section is about. Here's what sending looks like in my project:
CreateEmailOptions request = CreateEmailOptions.builder()
.from(fromName + " <" + fromEmail + ">")
.to(email)
.subject("📝 New article: " + post.getTitle())
.html(html)
.build();
CreateEmailResponse response = resend.emails().send(request);
log.info("Email sent, ID: {}", response.getId());
🧱 Interface and @ConditionalOnProperty
What it is. Business code depends on the EmailSender interface with a single method, and the specific implementation (Resend, SMTP, log) is chosen by a configuration property.
public interface EmailSender {
void send(EmailMessage message);
}
public record EmailMessage(String to, String subject, String html, String idempotencyKey) {}
@Service
@ConditionalOnProperty(name = "app.email.provider", havingValue = "resend")
public class ResendEmailSender implements EmailSender { ... }
@Service
@ConditionalOnProperty(name = "app.email.provider", havingValue = "smtp")
public class SmtpEmailSender implements EmailSender { ... }
@Service
@ConditionalOnProperty(name = "app.email.provider", havingValue = "log")
public class LoggingEmailSender implements EmailSender { ... } // writes email to log
Why so. A service that creates an ad request or publishes an article shouldn't know who will deliver the email. Its job is to say "send this email," not "build a request to Resend."
What this means in practice:
- Changing the provider is one environment variable (
APP_EMAIL_PROVIDER=smtp on Railway), without changing code and without a new release.
- Locally, emails go to the log (
app.email.provider=log in the dev profile) – you don't spend provider limits and don't send test emails to real people.
- A new implementation is one
send() method, not rewriting all email logic.
💡 From my experience: in my project, I keep a separate configuration for each provider – a Resend client in one class, a MailerLite client in another. The same @ConditionalOnProperty condition should be applied to these configurations: then the client bean is created only for the active provider. Without this, the application will require keys for all providers at once and won't start if even one is missing.
One piece of advice: don't set matchIfMissing = true on the log implementation. If you forget to set the variable in production, the application will silently "send" emails to the log. Without it, Spring simply won't start with an error about a missing EmailSender bean – and you'll find out about the problem immediately, not from users.
🎨 Email Templates with Thymeleaf
What it is. The email HTML is a regular Thymeleaf template in templates/email/, which is rendered into a string before sending.
Context context = new Context(Locale.of("uk"));
context.setVariable("post", post);
context.setVariable("unsubscribeUrl", unsubscribeUrl);
String html = templateEngine.process("email/new-post", context);
emailSender.send(new EmailMessage(email, subject, html, idempotencyKey));
Why so. The template lives in Git alongside the code: with change history, reviews, and the ability to roll back. It can be opened in a browser to see what the email looks like.
What this means in practice. Templates are provider-independent. If you store them in SendGrid's Dynamic Templates or Resend's Templates, you'll have to migrate and rewrite each template when moving. With your own templating engine, the provider receives already prepared HTML.
💡 From my experience: currently, my HTML emails are assembled using String.format directly in the provider class – 200+ lines of CSS and markup in Java. Changing a button text means editing a Java class and a new deployment. That's precisely why templates are moving to Thymeleaf.
And a practical detail about layout: email clients are not browsers. Gmail cuts out part of the CSS, and Outlook doesn't support flexbox. For emails, inline styles (style="...") and table-based layouts are more reliable.
⏱️ Asynchronous Sending via @Async
What it is. A method with @Async runs in a separate thread, and the user's request doesn't wait for the email to be sent to the provider.
@Async("emailExecutor")
public void sendCampaignCreatedNotification(String email, CampaignDto campaign) {
try {
emailSender.send(buildMessage(email, campaign));
} catch (Exception e) {
log.error("Failed to send email for {}", campaign.trackingCode(), e);
}
}
Why so. The SMTP or provider API can take a second or longer to respond, and sometimes not respond at all. The user who just created a request doesn't need to wait for this.
What this means in practice. The response comes immediately, and if the provider fails, the request is still created, the email just won't be delivered (we'll cover how to fix this in the retries section).
Three pitfalls to easily fall into:
- Self-invocation doesn't work. If a method with
@Async is called from another method in the same class, it will execute synchronously: the call bypasses the Spring proxy. An asynchronous method must be in a separate bean – in my case, it's NotificationService.
- An exception in a
void method will go unnoticed unless logged. Hence the try/catch inside.
- Set up your own thread pool with a limited queue and a clear name prefix (
email-), so that emails don't compete with other background tasks and are visible in logs.
🔒 Email After Transaction Commit
What it is. Instead of directly calling send, the service publishes an event, and an email is sent by a listener that triggers only after a successful commit.
Why so. Here's a real method from my project – creating an ad request:
@Transactional
public CampaignStatusResponse createCampaign(CampaignCreateRequest request) {
AdCampaign saved = campaignRepository.save(campaign);
notificationService.sendCampaignCreatedNotification(request.getContactEmail(), saved);
return adsMapper.toStatusResponse(saved);
}
It looks logical, but sending starts within the transaction. An asynchronous thread might send the email "Request successfully created" even before the commit. If the commit then fails (e.g., due to a uniqueness constraint that is checked when writing to the database), the client will receive an email with the code of a request that doesn't exist in the database.
How to do it correctly:
// In the service – only the event
@Transactional
public CampaignStatusResponse createCampaign(CampaignCreateRequest request) {
AdCampaign saved = campaignRepository.save(campaign);
events.publishEvent(new CampaignCreatedEvent(saved.getId(), request.getContactEmail()));
return adsMapper.toStatusResponse(saved);
}
// Email – after commit and in a separate thread
@Async("emailExecutor")
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void onCampaignCreated(CampaignCreatedEvent event) { ... }
What this means in practice. The email is sent only when the data is definitely in the database. Transaction rollback – no email.
Two details. Pass the ID and simple values to the event, not a JPA entity: after commit, it's already "detached" from the session, and accessing lazy fields will result in an exception. And if the event is published outside a transaction, the AFTER_COMMIT listener will silently ignore it – for such cases, there's the fallbackExecution = true parameter.
🔁 Retries and Errors
What it is. Categorizing errors into temporary ones that are worth retrying, and permanent ones that are futile to retry.
Why so. Provider errors come in two types:
- Temporary: 429 and 5xx. Request limit exceeded or provider outage. The request will most likely succeed in a second or two.
- Permanent: 400, 401, 403, 422. Incorrect address, invalid key, unverified domain. Retrying will yield the same error — only wasting your quota.
Therefore, when implementing a provider, it's advisable to convert errors into one of two custom exceptions:
if (status == 429 || status >= 500) {
throw new TransientEmailException(e); // can be retried
}
throw new PermanentEmailException(e); // retrying is futile
And only retry the former, with an increasing pause (backoff):
// Spring Boot 4 / Spring Framework 7 — built-in, plus @EnableResilientMethods in configuration
@Retryable(includes = TransientEmailException.class, maxRetries = 3, delay = 1000, multiplier = 2)
public void send(EmailMessage message) { ... }
// Spring Boot 3 — Spring Retry library, plus @EnableRetry
@Retryable(retryFor = TransientEmailException.class, maxAttempts = 4,
backoff = @Backoff(delay = 1000, multiplier = 2))
What this gives in practice. Short provider glitches are automatically "swallowed," while a broken email doesn't get stuck in retries.
Idempotency Key. There's an unpleasant scenario: the provider accepted the email, but the response was lost due to a timeout. You retry — and the client receives two identical emails. An idempotency key solves this: Resend remembers the key for 24 hours and doesn't send the email a second time for a repeated request with the same key. The key must uniquely describe the email:
String key = "campaign-created/" + campaignId; // for API — Idempotency-Key header
// for SMTP — Resend-Idempotency-Key header
What to do if the provider is down for longer. In-memory retries won't help if the outage lasts an hour or the application restarts. In such cases, it's more reliable to save emails to a table (status, number of attempts, next attempt time) and send them with a scheduled task. An email saved in the same transaction as the request will not be lost, neither during a provider outage nor during deployment.
❓ FAQ
What to choose for Spring Boot: SMTP or API provider?
SMTP — if independence from the provider is important and simple sending is needed. API — if idempotency, batch sending, tags, and email IDs are required. In both cases, hide the implementation behind an interface.
Why can't an email be sent directly inside a @Transactional method?
The email will be sent even if the transaction is later rolled back. The user will receive confirmation of an action that doesn't exist in the database. Use @TransactionalEventListener with the AFTER_COMMIT phase.
Why doesn't @Async work?
The most common reason is calling from the same class: it bypasses Spring proxies and executes synchronously. Move the asynchronous method to a separate bean and ensure @EnableAsync is enabled.
Which provider errors should be retried?
Only temporary ones: 429 (request limit) and 5xx (provider-side failure). 4xx errors like incorrect address or key are futile to retry.
Spring Retry or @Retryable with Spring Framework 7?
In Spring Boot 4 (Spring Framework 7), @Retryable is built into the framework itself and replaces the separate Spring Retry project. For Spring Boot 3, use the Spring Retry library.
✅ Conclusions
- SMTP provides independence from the provider, API offers more capabilities. Hide both options behind an interface.
- Switch providers using
@ConditionalOnProperty and environment variables — without changing code and without a new release.
- Keep email templates on your side — this way, migrating to another provider won't affect templates.
- Send asynchronously and only after the transaction commit.
- Retry only temporary errors, with backoff and an idempotency key, and for long outages, store emails in the database.
📚 Sources