Sitemap

Sending Emails with Dynamic SMTP in Laravel 8 Using Swift_Mailer

5 min readSep 2, 2025
Press enter or click to view image in full size

When building applications that handle multi-tenant systems, user-based SMTP settings, or SaaS platforms, you often face one challenge:

👉 How do I send emails using different SMTP credentials dynamically, instead of relying only on the .env file?

By default, Laravel loads mail settings from .env and uses them for every email. But what if each user (or company) in your system has their own SMTP server? For example:

  • User A wants to send emails using Gmail SMTP
  • User B wants to send emails using Outlook SMTP
  • User C wants to send emails using your default system SMTP

This is where dynamic SMTP mailer management comes in.

In this tutorial, we’ll learn step by step how to use Swift_Mailer (Laravel’s underlying mail engine in version 8) to send emails with user-specific SMTP configurations.

📌 Prerequisites

Before we dive in, you should already have:

  • A working Laravel 8 project
  • Basic knowledge of Mailables in Laravel
  • Configured .env file with a default mail setup (used as fallback)

📌 The Problem with Default Mail Setup

Normally, your .env file looks like this:

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=hello@example.com
MAIL_FROM_NAME="Example App"

And in Laravel, you simply send mail like this:

Mail::to('user@example.com')->send(new WelcomeMail());

This works fine if all emails are sent from one SMTP server.
But in real-world apps (like CRMs, ERPs, or SaaS platforms), every customer may want to use their own SMTP credentials.

That’s where we need a dynamic mailer system.

📌 Creating a Dynamic Mailer Service

We’ll create a MailerService that can switch SMTP settings at runtime.

👉 Here’s the full code:

<?php

namespace App\Services;
use Swift_SmtpTransport;
use Swift_Mailer;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;

class MailerService
{
/**
* Send an email using user-specific SMTP settings.
*
* @param object $smtp // object with host, port, encryption, username, password, from_email, from_name
* @param string|array $to
* @param \Illuminate\Mail\Mailable $mailable
* @return void
*/
public static function send($smtp, $to, $mailable)
{
if ($smtp) {
// Create SMTP transport dynamically
$transport = new Swift_SmtpTransport($smtp->host, $smtp->port, $smtp->encryption);
$transport->setUsername($smtp->username);
$transport->setPassword($smtp->password);
// Create SwiftMailer instance
$swiftMailer = new Swift_Mailer($transport);
// Create Laravel Mailer
$mailer = new Mailer('dynamic', App::get('view'), $swiftMailer, App::get('events'));
$mailer->alwaysFrom($smtp->from_address, $smtp->from_name ?? $smtp->from_address);
// Send the email
$mailer->to($to)->send($mailable);
} else {
// Fallback: use default .env SMTP
$transport = new Swift_SmtpTransport(env('MAIL_HOST'), env('MAIL_PORT'), env('MAIL_ENCRYPTION'));
$transport->setUsername(env('MAIL_USERNAME'));
$transport->setPassword(env('MAIL_PASSWORD'));
$swiftMailer = new Swift_Mailer($transport);
$mailer = new Mailer('dynamic', App::get('view'), $swiftMailer, App::get('events'));
$mailer->to($to)->send($mailable);
}
}
}

📌 Step-by-Step Breakdown

Let’s go line by line and understand what’s happening.

1. Import SwiftMailer Classes

use Swift_SmtpTransport;
use Swift_Mailer;
use Illuminate\Mail\Mailer;

Laravel’s Mail facade is actually built on SwiftMailer (in Laravel 9+, it switched to Symfony Mailer).
Here, we directly interact with SwiftMailer to create a custom mail transport.

2. Build a Transport with User Credentials

$transport = new Swift_SmtpTransport($smtp->host, $smtp->port, $smtp->encryption);
$transport->setUsername($smtp->username);
$transport->setPassword($smtp->password);

This dynamically sets:

  • SMTP Host (like smtp.gmail.com)
  • Port (587 / 465 / 25)
  • Encryption (tls or ssl)
  • Username & Password

3. Create a SwiftMailer Instance

$swiftMailer = new Swift_Mailer($transport);

This links the transport to SwiftMailer.

4. Create a Laravel Mailer

$mailer = new Mailer('dynamic', App::get('view'), $swiftMailer, App::get('events'));

Here we create a new Laravel Mailer instance named "dynamic" that uses:

  • The view system for rendering email templates
  • The events dispatcher for Laravel hooks

5. Set the From Address

$mailer->alwaysFrom($smtp->from_address, $smtp->from_name ?? $smtp->from_address);

This ensures every email sent from this dynamic mailer has the correct From address.

6. Send the Email

$mailer->to($to)->send($mailable);

Finally, we send the Mailable just like normal.

7. Default Fallback

If no custom SMTP is passed, it falls back to .env settings.

This is useful if some users don’t configure their SMTP.

📌 How to Use This Service

Let’s say you have a database table called user_smtp_settings where each user stores their SMTP credentials.
You can fetch them and pass to MailerService.

Example:

use App\Services\MailerService;
use App\Mail\WelcomeMail;

$user = Auth::user();
$smtp = (object) [
'host' => $user->smtp_host,
'port' => $user->smtp_port,
'encryption' => $user->smtp_encryption,
'username' => $user->smtp_username,
'password' => $user->smtp_password,
'from_address' => $user->smtp_from_email,
'from_name' => $user->smtp_from_name,
];
// Send email
MailerService::send($smtp, 'customer@example.com', new WelcomeMail());

If $smtp is null, it will fallback to .env.

📌 Example Mailable

Here’s a simple WelcomeMail mailable:

php artisan make:mail WelcomeMail
class WelcomeMail extends Mailable
{
public function build()
{
return $this->subject('Welcome to Our App')
->view('emails.welcome');
}
}

And in resources/views/emails/welcome.blade.php:

<h1>Welcome!</h1>
<p>We’re glad to have you on board 🎉</p>

📌 When Should You Use Dynamic SMTP?

Dynamic SMTP is useful when:

  • You’re building a SaaS app where each customer wants to send emails via their own SMTP.
  • You need white-label email delivery.
  • You want higher deliverability (sending from users’ real domains instead of a shared server).
  • You manage multiple brands or tenants in the same app.

📌 Things to Keep in Mind

  1. ✅ Always validate SMTP credentials before saving them (e.g., test connection).
  2. ✅ Avoid storing SMTP passwords in plain text — consider encryption.
  3. ✅ Use queues for sending emails to avoid blocking requests.
  4. ✅ In Laravel 9+, SwiftMailer was replaced with Symfony Mailer, so the approach is slightly different.

📌 Conclusion

With this setup, you now have a flexible email system in Laravel 8 that can send emails from different SMTP servers on the fly.

  • Default: Use .env mail settings
  • Custom: Use per-user SMTP settings dynamically

This makes your app scalable, flexible, and tenant-ready.

🔥 Now you can build CRMs, ERPs, or SaaS apps where every customer sends emails with their own SMTP — and you don’t have to hardcode anything.

Go forth and get more out of your content. Go forth and conquer Medium! (and while you’re at it, follow me on Medium! and feel free to Subscribe)

Found this post useful? Kindly tap the 👏 button below! :)

🌟 Enjoy my blogging content? Support my work by buying me a virtual coffee on BuyMeACoffee! Your contributions help fuel insightful tech articles. Join hands in making coding more accessible and exciting for all. https://www.buymeacoffee.com/arjunamrutiya🚀

--

--

ArjunAmrutiya
ArjunAmrutiya

Written by ArjunAmrutiya

👋 Hey there! I'm Arjun Amrutiya, a passionate web developer and blogger who loves all things PHP, Laravel and Vue.js. Welcome to my Medium account!

No responses yet