How to change mail configuration before sending a mail in the controller using Laravel?

You can set/change any configuration on the fly using Config::set:

Config::set('key', 'value');

So, to set/change the port in mail.php you may try this:

Config::set('mail.port', 587); // default

Note: Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests. Read more.

Update: A hack for saving the config at runtime.


The selected answer didn't work for me, I needed to add the following for the changes to be registered.

Config::set('key', 'value');
(new \Illuminate\Mail\MailServiceProvider(app()))->register();

I know is kind of late but an approach could be providing a swift mailer to the laravel mailer.

<?php

$transport = (new \Swift_SmtpTransport('host', 'port'))
    ->setEncryption(null)
    ->setUsername('username')
    ->setPassword('secret');

$mailer = app(\Illuminate\Mail\Mailer::class);
$mailer->setSwiftMailer(new \Swift_Mailer($transport));

$mail = $mailer
    ->to('[email protected]')
    ->send(new OrderShipped);

Tags:

Php

Email

Laravel