我的用例与此类似,简而言之,我只是想在运行时自动配置 mailgun 发送域,方法是查看消息的 from 地址字段中设置的域(我在使用Mail::from(...)->send(...) 发送之前即时设置。如果他们将消息中的发件人地址设置为与 mailgun 发送域匹配,这将解决 OP 的用例,这很可能应该这样做。
我的解决方案注册了一个替代 MailgunTransport,它会覆盖内置的 MailgunTransport 并在发送前设置域。这样我只需要在我的mail.php注册新驱动,然后调用Mail::send或Mail::queue即可。
配置\mail.php:
'driver' => env('MAIL_DRIVER', 'mailgun-magic-domain')
providers\MailgunMagicDomainProvider:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Mail\Transport\MailgunTransport;
use Swift_Mime_Message;
use Illuminate\Support\Arr;
use GuzzleHttp\Client as HttpClient;
class MailgunMagicDomainProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$swiftTransport = $this->app['swift.transport'];
$swiftTransport->extend('mailgun-magic-domain', function($app) {
$config = $app['config']->get('services.mailgun', []);
$client = new HttpClient(Arr::add(
Arr::get($config, 'guzzle', []), 'connect_timeout', 60
));
return new MailgunTransportWithDomainFromMessage(
$client,
$config['secret'],
$config['domain'] // <- we have to pass this in to avoid re-writing the whole transport, but we'll be dynamically setting this before each send anyway
);
});
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
}
}
/**
* Overrides the built in Illuminate\Mail\Transport\MailgunTransport but doesnt pull the
* mailgun sending domain from the config, instead it uses the domain in the from address
* to dynamically set the mailgun sending domain
*/
class MailgunTransportWithDomainFromMessage extends MailgunTransport
{
/**
* {@inheritdoc}
*/
public function send(Swift_Mime_Message $message, &$failedRecipients = null)
{
$this->setDomain($this->getDomainFromMessage($message));
return parent::send($message, $failedRecipients);
}
protected function getDomainFromMessage(Swift_Mime_Message $message)
{
$fromArray = $message->getFrom();
if (count($fromArray) !== 1) {
throw new \Exception('Cannot use the mailgun-magic-domain driver when there isn\'t exactly one from address');
}
return explode('@', array_keys($fromArray)[0])[1];
}
}
config/app.php:
'providers' => [
...
\App\Providers\MailgunMagicDomainProvider::class
],