Laravel Tutorials

Dynamic Mailer Configuration in Laravel with Mail::build

Published
Dynamic Mailer Configuration in Laravel with Mail::build image

Need to configure mailers dynamically? Laravel's Mail::build method lets you create mailers on the fly! Let's explore this flexible approach to email configuration.

Basic Usage

Here's how to create a mailer dynamically:

use Illuminate\Support\Facades\Mail;

$mailer = Mail::build([
    'transport' => 'smtp',
    'host' => '127.0.0.1',
    'port' => 587,
    'encryption' => 'tls',
    'username' => 'usr',
    'password' => 'pwd',
    'timeout' => 5,
]);

$mailer->send($mailable);

Real-World Example

Here's how you might use it in a multi-tenant application:

class TenantMailService
{
    public function sendWithTenantConfig(
        Tenant $tenant, 
        Mailable $mailable
    ) {
        $mailerConfig = $tenant->email_settings;

        $mailer = Mail::build([
            'transport' => 'smtp',
            'host' => $mailerConfig->smtp_host,
            'port' => $mailerConfig->smtp_port,
            'encryption' => $mailerConfig->encryption,
            'username' => decrypt($mailerConfig->username),
            'password' => decrypt($mailerConfig->password),
            'from' => [
                'address' => $tenant->email,
                'name' => $tenant->company_name
            ]
        ]);

        try {
            $mailer->send($mailable);
            
            Log::info("Email sent for tenant: {$tenant->id}", [
                'mailable' => get_class($mailable)
            ]);
            
        } catch (Exception $e) {
            Log::error("Failed to send email for tenant: {$tenant->id}", [
                'error' => $e->getMessage()
            ]);
            
            throw $e;
        }
    }
}

// Usage
class NewsletterController extends Controller
{
    public function send(
        Tenant $tenant, 
        TenantMailService $mailService
    ) {
        $newsletter = new TenantNewsletter($tenant);
        
        $mailService->sendWithTenantConfig(
            $tenant, 
            $newsletter
        );
        
        return back()->with('success', 'Newsletter queued for sending');
    }
}

Dynamic mailer configuration is perfect for multi-tenant applications, custom email providers, or any scenario where mail settings need to be configured at runtime.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Laravel AutoBuilder: Build Visual Automation Workflows image

Laravel AutoBuilder: Build Visual Automation Workflows

Read article
Pun: Format, Lint, and Analyze PHP With One Rust Binary image

Pun: Format, Lint, and Analyze PHP With One Rust Binary

Read article
Form Request Model Lookups and PHP 8.6 Support in Laravel 13.44 image

Form Request Model Lookups and PHP 8.6 Support in Laravel 13.44

Read article
Generate Laravel Validation Rules From a JSON Schema image

Generate Laravel Validation Rules From a JSON Schema

Read article
Laravel Suspicious Login: Detect and Block Risky Logins image

Laravel Suspicious Login: Detect and Block Risky Logins

Read article
Decide with Jev: Make Failed AI Requests Safe in Laravel image

Decide with Jev: Make Failed AI Requests Safe in Laravel

Read article