Laravel Mail Failover: Using Multiple SMTP Servers the Built-In Way

Shaz3e laravel mail failover cover showing a failed primary SMTP transport followed by an attempt on the next transport.

If your app sends password resets, invoices or order updates through one SMTP server, that server is a single point of failure. When it rejects a login, hits a rate limit or simply times out, the user never gets the email and you usually find out from a support ticket.

A while back I wrote a dev.to post, sending emails in Laravel using multiple SMTP servers, that solved this with a custom service: try the main mailer, catch the exception, send again through a backup. It worked. But Laravel now ships two mail transports that do most of this in config alone, failover and roundrobin. This post is the refreshed version: the built-in way first, then when a small custom service still earns its place, with tests for both.

It belongs to my wider guide on Laravel performance optimization for production apps, because a mail path that stalls or fails quietly is a production problem, not just a config detail.

What this post covers

Tested versions

ToolVersion
Laravel Framework13.40.0 (fresh laravel/laravel skeleton)
PHP8.4.27 CLI
Mail transportSymfony Mailer (bundled with Laravel)
TestsPHPUnit through php artisan test, 7 tests passing

The tests swap the real SMTP servers for two tiny in-memory transports: one that always throws and one that records what it receives. I didn’t send anything through a live provider for this post, so treat host names and ports as placeholders and copy the real ones from your provider.

The failover mailer

The failover transport takes a list of mailers you already defined in config/mail.php. It sends through the first one. If that throws a transport error, it moves to the next, and so on down the list. Under the hood Laravel builds Symfony’s FailoverTransport, which is documented in the Symfony Mailer docs.

Add a second SMTP mailer next to the default one, then point the failover list at both, with the log mailer last as a safety net while you’re testing:

'mailers' => [

    'smtp' => [
        'transport' => 'smtp',
        'host' => env('MAIL_HOST', '127.0.0.1'),
        'port' => env('MAIL_PORT', 2525),
        'username' => env('MAIL_USERNAME'),
        'password' => env('MAIL_PASSWORD'),
        'timeout' => null,
    ],

    'smtp_backup' => [
        'transport' => 'smtp',
        'scheme' => env('MAIL_BACKUP_SCHEME'),
        'host' => env('MAIL_BACKUP_HOST'),
        'port' => env('MAIL_BACKUP_PORT', 587),
        'username' => env('MAIL_BACKUP_USERNAME'),
        'password' => env('MAIL_BACKUP_PASSWORD'),
        'timeout' => 10,
    ],

    'failover' => [
        'transport' => 'failover',
        'mailers' => [
            'smtp',
            'smtp_backup',
            'log',
        ],
        'retry_after' => env('MAIL_FAILOVER_RETRY_AFTER', 60),
    ],

    // ...
],

Then make it the default in .env:

MAIL_MAILER=failover

MAIL_HOST=smtp.primary-provider.example
MAIL_PORT=587
MAIL_USERNAME=...
MAIL_PASSWORD=...

MAIL_BACKUP_HOST=smtp.backup-provider.example
MAIL_BACKUP_PORT=587
MAIL_BACKUP_USERNAME=...
MAIL_BACKUP_PASSWORD=...

That’s the whole change for most apps. Every Mail::to(...)->send(...) and every notification that uses the mail channel now goes through the failover chain. No controller or mailable has to know about it.

Two things are worth doing on the backup. Give it an explicit timeout, because the default can leave a worker waiting a long time on a server that never answers. And make sure the backup’s sending domain is authenticated with SPF and DKIM too. A backup that lands everything in spam isn’t really a backup. The Diligent Creators blog has an {link(DC, ’email deliverability checklist’)} that covers the DNS side.

What retry_after actually does

retry_after is in seconds, and Laravel defaults it to 60 if you leave it out. When a mailer in the list fails, the transport marks it as dead and skips it for that many seconds. The next message goes straight to the backup instead of waiting on the broken primary again. Each failure is also written to your Laravel log as an error, so a fallback doesn’t happen silently.

The part that’s easy to miss: once the failover transport has moved to the backup, it stays on the backup for as long as that object lives and the backup keeps working. It doesn’t switch back the moment retry_after runs out. The primary only comes back into play when the backup fails, or when a fresh transport is built. For most apps that’s fine, but don’t expect traffic to drift back to the primary on its own inside a long-running worker.

One detail surprised me when I first read the Symfony code: that dead list lives in memory, inside the transport object. A long-running queue worker remembers that the primary is down. A normal web request builds a fresh transport each time, so it tries the primary first on every request. If the primary fails by hanging rather than refusing quickly, that’s another reason to keep its timeout short.

If every mailer in the list fails, you get a TransportException saying all transports failed. That’s what you want. It means a queued mail job fails and retries, instead of pretending the email went out.

The roundrobin mailer

Roundrobin uses the same config shape but a different goal. Instead of always starting with the first mailer, it spreads messages across all of them, and it still skips a mailer that just failed. Use it when you have two providers you trust equally and you want to share the load or stay under each one’s sending limit.

'roundrobin' => [
    'transport' => 'roundrobin',
    'mailers' => [
        'smtp',
        'smtp_backup',
    ],
    'retry_after' => 60,
],

Note that roundrobin starts at a random mailer, so you can’t predict which provider sends the first message. If one provider is your main account and the other is a paid emergency route, stick with failover.

failoverroundrobin
OrderAlways tries the first healthy mailerRotates through mailers, random start
Best forMain provider plus a backupTwo equal providers, load sharing
On errorMoves to the next mailerMoves to the next mailer
Dead mailerSkipped for retry_after secondsSkipped for retry_after seconds

My older custom approach, refreshed

The original dev.to post wrapped Mail::mailer('smtp') in a try/catch and fell back to Mail::mailer('backup_smtp'). With the built-in transports, I’d no longer start there. I’d still reach for a small service in a few cases:

  • You need to know which mailer actually sent a message, for example to store it on an audit row.
  • You want to log or alert on every fallback with your own context, such as the tenant or the mail type.
  • Different mail types need different chains, and you’d rather not define a failover mailer for each one.

Here’s the cleaned-up version. It reads the same list the failover mailer uses, catches only transport errors, logs each fallback, and returns the name of the mailer that worked:

<?php

namespace App\Services\Mail;

use Illuminate\Contracts\Mail\Mailable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;

class ResilientMailer
{
    /**
     * @param  array<int, string>  $mailers  Mailer names from config/mail.php, in priority order.
     */
    public function __construct(private array $mailers)
    {
    }

    /**
     * Try each mailer in order and return the name of the one that sent the message.
     */
    public function send(string $to, Mailable $mailable): string
    {
        $last = null;

        foreach ($this->mailers as $name) {
            try {
                Mail::mailer($name)->to($to)->sendNow($mailable);

                return $name;
            } catch (TransportExceptionInterface $e) {
                $last = $e;

                Log::warning('Mailer failed, trying the next one', [
                    'mailer' => $name,
                    'error' => $e->getMessage(),
                ]);
            }
        }

        throw $last ?? new \RuntimeException('No mailers configured.');
    }
}

It’s registered once in AppServiceProvider so the list stays in config:

$this->app->singleton(ResilientMailer::class, fn () => new ResilientMailer(
    config('mail.mailers.failover.mailers', ['smtp'])
));

Two fixes over the old version. It catches TransportExceptionInterface instead of every exception, so a bug in your mailable doesn’t trigger a pointless resend through the backup. And it rethrows when everything fails, so the caller can’t miss it. It uses sendNow on purpose: the service is meant to run inside a queued job you control, not to queue again.

Queue the mail, not the request

The old post sent mail inline, inside the HTTP request. With failover that’s worse than it sounds: if the primary hangs until its timeout, the user waits for it. Implement ShouldQueue on the mailable and let a worker deal with slow or broken servers:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class InvoiceReady extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    public int $tries = 3;

    public array $backoff = [30, 120];

    public function __construct(public string $invoiceNumber)
    {
    }

    public function envelope(): Envelope
    {
        return new Envelope(subject: "Invoice {$this->invoiceNumber} is ready");
    }

    public function content(): Content
    {
        return new Content(htmlString: "<p>Your invoice {$this->invoiceNumber} is ready.</p>");
    }
}

With $tries and $backoff, a total outage on both providers becomes a few spaced retries instead of a lost email. If you haven’t set up workers for production yet, my post on Laravel queue workers with Supervisor covers that part, and retries and timeouts for Laravel HTTP clients uses the same thinking for API-based mail providers.

Testing failover without a real SMTP server

You don’t need two SMTP accounts to test this. Register two custom transports in the test with Mail::extend(): one that always throws a TransportException, and one that keeps the messages it gets.

class BrokenTransport extends AbstractTransport
{
    public int $attempts = 0;

    protected function doSend(SentMessage $message): void
    {
        $this->attempts++;

        throw new TransportException('Connection to primary SMTP refused.');
    }

    public function __toString(): string
    {
        return 'broken://';
    }
}

The feature test wires them into a failover and a roundrobin mailer, then checks where the mail ended up:

public function test_failover_mailer_sends_through_backup_when_primary_fails(): void
{
    Mail::mailer('failover')->to('client@example.com')->send(new InvoiceReady('INV-1001'));

    $this->assertSame(1, $this->primary->attempts);
    $this->assertCount(1, $this->backup->sent);
}

public function test_failover_skips_a_dead_transport_until_retry_after_passes(): void
{
    $mailer = Mail::mailer('failover');

    $mailer->to('a@example.com')->send(new InvoiceReady('INV-1'));
    $mailer->to('b@example.com')->send(new InvoiceReady('INV-2'));

    $this->assertSame(1, $this->primary->attempts);
    $this->assertCount(2, $this->backup->sent);
}

public function test_roundrobin_spreads_messages_across_mailers(): void
{
    $mailer = Mail::mailer('roundrobin');

    foreach (range(1, 4) as $i) {
        $mailer->to("user{$i}@example.com")->send(new InvoiceReady("INV-{$i}"));
    }

    $this->assertCount(2, $this->backup->sent);
    $this->assertCount(2, $this->second->sent);
}

public function test_custom_service_falls_back_and_reports_which_mailer_sent(): void
{
    $service = new ResilientMailer(['primary', 'backup']);

    $used = $service->send('client@example.com', new InvoiceReady('INV-2001'));

    $this->assertSame('backup', $used);
    $this->assertCount(1, $this->backup->sent);
}

public function test_invoice_mail_is_queued_not_sent_inline(): void
{
    Mail::fake();

    Mail::to('client@example.com')->send(new InvoiceReady('INV-3001'));

    Mail::assertQueued(InvoiceReady::class, fn ($mail) => $mail->invoiceNumber === 'INV-3001');
    Mail::assertNothingSent();

The second test is the one I like most. It proves the retry_after behaviour: after the first failure, the broken primary isn’t even tried for the second message. The last test uses Mail::fake() to confirm the invoice is queued, not sent inside the request. All seven tests in the demo app pass on Laravel 13.40.0 and PHP 8.4.27.

A short checklist

  1. Define the backup as its own mailer in config/mail.php, with its own credentials in .env.
  2. Set MAIL_MAILER=failover (or roundrobin) and keep retry_after explicit.
  3. Give each SMTP mailer a short timeout so a hung server fails fast.
  4. Authenticate the backup’s sending domain with SPF and DKIM before you need it.
  5. Queue mailables, and give the job a few tries with backoff.
  6. Drop log from the production chain once you trust the backup, or you’ll hide real outages in a log file.
  7. Test the chain with a throwing transport, not by turning off a real server.

On shared or reseller hosting, check that outbound SMTP ports aren’t blocked before you count on a third-party backup. My Laravel hosting requirements post lists what to ask your host, and if you also need proper mailboxes for the sending domain, ResellerBytes has a plain guide on professional email addresses.

FAQ

Which Laravel versions have the failover mailer?

Failover has been in Laravel since version 8, and roundrobin arrived later in the 10.x line. Both are in the current Laravel mail docs. I tested everything here on Laravel 13.40.0.

Can I mix SMTP with an API mailer like SES or Postmark?

Yes. The list holds mailer names, and any configured mailer works, including ses, postmark, resend or sendmail. Mixing an SMTP primary with an API backup is a sensible setup, because the two fail for different reasons.

Do notifications use the failover mailer too?

Yes, as long as the mail channel uses the default mailer. If a notification picks a specific mailer with ->mailer('smtp'), it skips the chain, so point it at failover instead.

Does failover help when an email bounces?

No. Failover reacts to transport errors while sending, such as a refused connection, failed login or timeout. A bounce happens later, after the server accepted the message. Handle bounces with your provider’s webhooks or bounce reports.

Should I delete my custom fallback service?

If it only does try-primary-then-backup, yes. Replace it with the failover mailer and delete the code. Keep a service only when you need to know which mailer sent, or want custom logging on each fallback.


I’m Shahrukh Akhtar (Shaz3e), CTO & Co-Founder of Diligent Creators Pvt. Ltd., a Technology Executive & Product Builder. I run client delivery and build SaaS products, including EloSync. You can find me on X, LinkedIn, Peerlist and GitHub.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *