如何在使用 Laravel 在控制器中发送邮件之前更改邮件配置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23438342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:27:43  来源:igfitidea点击:

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

phpemaillaravel

提问by jibe

I'm using Laravel 4, I would like to change the mail configuration (like driver/host/port/...) in the controller as I would like to save profiles in databases with different mail configuration. This is the basic send mail using configuration from config/mail.php

我正在使用 Laravel 4,我想更改控制器中的邮件配置(如驱动程序/主机/端口/...),因为我想将配置文件保存在具有不同邮件配置的数据库中。这是使用 config/mail.php 配置的基本发送邮件

Mail::send(
    'emails.responsable.password_lost',
    array(),
    function($message) use ($responsable){
        $message->to($responsable->email, $responsable->getName());
        $message->subject(Lang::get('email.password_lost'));
    });

I've tried to put something like but it didn't work

我试过放一些类似的东西,但没有用

 $message->port('587');

Thanks for your support!

谢谢您的支持!

Jean

回答by The Alpha

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

您可以使用Config::set以下命令即时设置/更改任何配置:

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

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

因此,要设置/更改端口,mail.php您可以尝试以下操作:

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.

更新在运行时保存配置的技巧。

回答by Hillel Coren

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();

回答by Francisco Daniel

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

我知道有点晚了,但一种方法可能是为 laravel 邮件程序提供一个快速邮件程序。

<?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);