Various guides exist on how to do this in Laravel, but all the ones I found (https://laravel-news.com/allowing-users-to-send-email-with-their-own-smtp-settings-in-laravel and https://blog.creekorful.org/2021/11/laravel-dynamic-smtp-mail-configuration/) worked only up to Laravel 8. The reason is that in v9 the Swift Mailer was no longer supported in favor of https://laravel.com/docs/9.x/releases#symfony-mailer. The Laravel docs show how to write your own custom transports, but that's not what we need here.

namespace App\Extensions; use Illuminate\Mail\MailManager; class UserMailManager extends MailManager { public function __construct($app, private readonly array $customConfig) { parent::__construct($app); } protected function getConfig(string $name) { return $this->customConfig; }}

public function sendMail(Mailable $mailable) { if ($this->smtp_enabled) { $smtpParams = [ 'transport' => 'smtp', 'host' => $this->smtp_params['smtp_host']?? null, 'port' => $this->smtp_params['smtp_port']?? null, 'username' => $this->smtp_params['smtp_user']?? null, 'password' => $this->smtp_params['smtp_password']?? null, 'timeout' => null, 'verify_peer' => false, ]; /** @var Mailer $mailer */ $mailer = app('creator.mailer', $smtpParams); $mailer->send($mailable); } else { Mail::send($mailable); }} #using-the-mailer-with-custom-smtp-params Using the mailer with custom SMTP params
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Community Partners