Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending from multiple Mailgun domains using Laravel Mail facade

I'm using the Laravel 4's Mail::queue() to send emails, using the built in Mailgun driver. The problem is that there are multiple Mailgun domains I would like to be able to send emails from, but the domain must be set in app/config/services.php. Since I'm using Mail::queue(), I can't see how to dynamically set that configuration variable.

Is there any way to do what I'm asking? Ideally, I'd like to be able to pass in the domain when I call Mail::queue() (the Mailgun api key is the same for all the domains I want to send from).

like image 836
Will Durney Avatar asked Feb 25 '15 22:02

Will Durney


1 Answers

I used Macros to add dynamic configuration. I don't remember if this can be done in Laravel 4 but works on 5.

Register macro in service provider (AppServiceProvider)

public function boot()
{
    Mail::macro('setConfig', function (string $key, string $domain) {

        $transport = $this->getSwiftMailer()->getTransport();
        $transport->setKey($key);
        $transport->setDomain($domain);

        return $this;
    });
}

Then I can use like this:

\Mail::setConfig($mailgunKey, $mailgunDomain)->to(...)->send(...)

In your case

\Mail::setConfig($mailgunKey, $mailgunDomain)->to(...)->queue(...)
like image 59
Mirceac21 Avatar answered Sep 22 '22 18:09

Mirceac21