Dynamic Mailer Configuration in Laravel with Mail::build

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.


The post Dynamic Mailer Configuration in Laravel with Mail::build appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.

Read more

© 2024 Extly, CB - All rights reserved.