Laravel Mail::send() sending to multiple to or bcc addresses

haakym picture haakym · Oct 27, 2014 · Viewed 138.5k times · Source

I can't seem to successfully send to multiple addresses when using Laravel's Mail::send() callback, the code does however work when I only specify one recipient.

I've tried chaining:

// for example
$emails = array("[email protected]", "[email protected]");
$input = Input::all();

Mail::send('emails.admin-company', array('body' => Input::get('email_body')), 
function($message) use ($emails, $input) {
    $message
    ->from('[email protected]', 'Administrator')
    ->subject('Admin Subject');

        foreach ($emails as $email) {
            $message->to($email);
        }
});

and passing an array:

// for example
$emails = array("[email protected]", "[email protected]");
$input = Input::all();

Mail::send('emails.admin-company', array('body' => Input::get('email_body')), 
    function($message) use ($emails, $input) {
        $message
        ->from('[email protected]', 'Administrator')
        ->subject('Admin Subject');

        $message->to($emails);
});

but neither seem to work and I get failure messages when returning Mail::failures(), a var_dump() of Mail::failures() shows the email addresses that I tried to send to, for example:

array(2) {
  [0]=>
  string(18) "[email protected]"
  [1]=>
  string(18) "[email protected]"
}

Clearly doing something wrong, would appreciate any help as I'm not understanding the API either: http://laravel.com/api/4.2/Illuminate/Mail/Message.html#method_to

I realise I could put the Mail::send() method in a for/foreach loop and Mail::send() for each email address, but this doesn't appear to me to be the optimal solution, I was hoping I would also be able to ->bcc() to all addresses once everything was working so the recipients wouldn't see who else the mail is being sent to.

Answer

Marcin Nabiałek picture Marcin Nabiałek · Oct 27, 2014

I've tested it using the following code:

$emails = ['[email protected]', '[email protected]','[email protected]'];

Mail::send('emails.welcome', [], function($message) use ($emails)
{    
    $message->to($emails)->subject('This is test e-mail');    
});
var_dump( Mail:: failures());
exit;

Result - empty array for failures.

But of course you need to configure your app/config/mail.php properly. So first make sure you can send e-mail just to one user and then test your code with many users.

Moreover using this simple code none of my e-mails were delivered to free mail accounts, I got only emails to inboxes that I have on my paid hosting accounts, so probably they were caught by some filters (it's maybe simple topic/content issue but I mentioned it just in case you haven't received some of e-mails) .