phplaravellaravel-4

multiple mail configurations


I configured Laravel's mail service with the Mandrill driver. No problems here!

Now, at a certain point in my application, I need to send mail via Gmail.

I did something like:

// backup current mail configs
$backup = Config::get('mail');

// rewrite mail configs to gmail stmp
$new_configs = array(
    'driver' => 'smtp',
    // ... other configs here
);
Config::set('mail', $new_configs);

// send the email
Mail::send(...

// restore configs
Config::set('mail', $backup);

This doesn't work, Laravel always uses the mandrill configurations. It looks like he initiates mail service at script startup and ignores whatever you do during execution.

How do you change mail service configs/behaviour during execution?


Solution

  • You can create a new Swift_Mailer instance and use that:

    // Backup your default mailer
    $backup = Mail::getSwiftMailer();
    
    // Setup your gmail mailer
    $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl');
    $transport->setUsername('your_gmail_username');
    $transport->setPassword('your_gmail_password');
    // Any other mailer configuration stuff needed...
    
    $gmail = new Swift_Mailer($transport);
    
    // Set the mailer as gmail
    Mail::setSwiftMailer($gmail);
    
    // Send your message
    Mail::send();
    
    // Restore your original mailer
    Mail::setSwiftMailer($backup);