Home >Backend Development >PHP Tutorial >Dynamic Mailer Configuration in Laravel with Mail::build

Dynamic Mailer Configuration in Laravel with Mail::build

Karen Carpenter
Karen CarpenterOriginal
2025-03-06 02:30:09903browse

Dynamic Mailer Configuration in Laravel with Mail::build

Leverage Laravel's Mail::build for dynamic mailer configuration! This flexible approach simplifies email setup in various scenarios.

Basic Usage

Creating a dynamic mailer is straightforward:

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 Application: Multi-Tenant Setup

Consider 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("Email failed for tenant: {$tenant->id}", ['error' => $e->getMessage()]);
            throw $e;
        }
    }
}

// Usage within a controller
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!');
    }
}

This method is ideal for multi-tenant applications, custom email providers, or any situation requiring runtime email configuration adjustments.

The above is the detailed content of Dynamic Mailer Configuration in Laravel with Mail::build. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn