Laravel动态更新电子邮件配置

时间:2016-02-08 10:19:49

标签: php email laravel-4 mailgun

我需要能够使用Mailgun从一个域发送电子邮件,切换设置,然后从另一个域发送另一个。但是,在发送第二封电子邮件之前更新设置不起作用,第二封电子邮件仍会使用第一封电子邮件设置发送。

初始设置在Config.mailConfig.services中设置,这一切都正常。

// send first email
try { 
    Mail::send(--stuff here--) 
} catch (Exception $e) { ... }

// update config using the sandbox account details
Config::set('mail.username', 'postmaster@secret.mailgun.org');
Config::set('mail.password', 'password');
Config::set('services.mailgun.domain', 'domain.mailgun.org'); 
Config::set('services.mailgun.secret', 'key-secret');

// send second email
try { 
    Mail::send(--stuff here--) 
} catch (Exception $e) { ... }
// Second email has now been sent using the first emails config settings 

如果我注释掉第一封电子邮件发送,则更改上述设置,第二封电子邮件将从沙盒帐户中正确发送。如果我留下第一封电子邮件,它将从我在MailGun上的域发送。

有没有人有这方面的经验?

3 个答案:

答案 0 :(得分:6)

感谢上面的回答。不幸的是,Laravel 5.4 share()被删除了,这将不再适用。上面代码的更新版本使用单例代替share()在5.4中工作。

config(['mail.driver' => 'mailgun']);
config(['services.mailgun.domain' => mail_domain]);
config(['services.mailgun.secret' => mail_secret]);

$app = \App::getInstance();

$app->singleton('swift.transport', function ($app) {
    return new \Illuminate\Mail\TransportManager($app);
});

$mailer = new \Swift_Mailer($app['swift.transport']->driver());
\Mail::setSwiftMailer($mailer);

\Mail::to(me@example.com)->send(new TrialCreated($params));

答案 1 :(得分:1)

    config([
        'mail.host' => 'smtp.yandex.ru',
        'mail.port' => 465,
        'mail.encryption' =>'ssl',
        'mail.username' => 'username',
        'mail.password' => 'password'
    ]);

    $app = App::getInstance();

    $app['swift.transport'] = $app->share(function ($app) {
        return new TransportManager($app);
    });

    $mailer = new \Swift_Mailer($app['swift.transport']->driver());
    Mail::setSwiftMailer($mailer);

    $msg = Mail::send('mail.view', ['key' => 'value'], function(Message $message) {
        $message
            ->to('user@mail.com', 'Name')
            ->subject('Subject');
    });

答案 2 :(得分:0)

我的情况要简单一些。我只需要选择其他驱动程序。这在Laravel 6.10中有效。也许您可以对其进行调整以满足您的需求。

app / Traits / MailDriver.php

dataGridView1.Columns.Add(dgvcbcGender);

app / Mail / TestMail.php

namespace App\Traits;

trait MailDriver
{
    public function driver($driver)
    {
        config()->set('mail.driver', $driver); // Configure as necessary.

        app()->singleton('swift.transport', function ($app) {
            return new \Illuminate\Mail\TransportManager($app);
        });

        \Mail::setSwiftMailer(new \Swift_Mailer(app()['swift.transport']->driver()));

        return $this;
    }
}
相关问题