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

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.

This question is related to php email laravel laravel-4

The answer is


the accepted answer does not work any longer with laravel 5.3 because mailable tries to access ->email and results in

ErrorException in Mailable.php line 376: Trying to get property of non-object

a working code for laravel 5.3 is this:

$users_temp = explode(',', '[email protected],[email protected]');
    $users = [];
    foreach($users_temp as $key => $ut){
      $ua = [];
      $ua['email'] = $ut;
      $ua['name'] = 'test';
      $users[$key] = (object)$ua;
    }
 Mail::to($users)->send(new OrderAdminSendInvoice($o));

I am using Laravel 5.6 and the Notifications Facade.

If I set a variable with comma separating the e-mails and try to send it, I get the error: "Address in mail given does not comply with RFC 2822, 3.6.2"

So, to solve the problem, I got the solution idea from @Toskan, coding the following.

        // Get data from Database
        $contacts = Contacts::select('email')
            ->get();

        // Create an array element
        $contactList = [];
        $i=0;

        // Fill the array element
        foreach($contacts as $contact){
            $contactList[$i] = $contact->email;
            $i++;
        }

        .
        .
        .

        \Mail::send('emails.template', ['templateTitle'=>$templateTitle, 'templateMessage'=>$templateMessage, 'templateSalutation'=>$templateSalutation, 'templateCopyright'=>$templateCopyright], function($message) use($emailReply, $nameReply, $contactList) {
                $message->from('[email protected]', 'Some Company Name')
                        ->replyTo($emailReply, $nameReply)
                        ->bcc($contactList, 'Contact List')
                        ->subject("Subject title");
            });

It worked for me to send to one or many recipients.


This works great - i have access to the request object and the email array

        $emails = ['[email protected]', '[email protected]'];
        Mail::send('emails.lead', ['name' => $name, 'email' => $email, 'phone' => $phone], function ($message) use ($request, $emails)
        {
            $message->from('[email protected]', 'Joe Smoe');
//            $message->to( $request->input('email') );
            $message->to( $emails);
            //Add a subject
            $message->subject("New Email From Your site");
        });

Try this:

$toemail = explode(',', str_replace(' ', '', $request->toemail));

With Laravel 5.6, if you want pass multiple emails with names, you need to pass array of associative arrays. Example pushing multiple recipients into the $to array:

$to[] = array('email' => $email, 'name' => $name);

Fixed two recipients:

$to = [['email' => '[email protected]', 'name' => 'User One'], 
       ['email' => '[email protected]', 'name' => 'User Two']];

The 'name' key is not mandatory. You can set it to 'name' => NULL or do not add to the associative array, then only 'email' will be used.


If you want to send emails simultaneously to all the admins, you can do something like this:

In your .env file add all the emails as comma separated values:

[email protected],[email protected],[email protected]

so when you going to send the email just do this (yes! the 'to' method of message builder instance accepts an array):

So,

$to = explode(',', env('ADMIN_EMAILS'));

and...

$message->to($to);

will now send the mail to all the admins.


In a scenario where you intend to push a single email to different recipients at one instance (i.e CC multiple email addresses), the solution below works fine with Laravel 5.4 and above.

Mail::to('[email protected]')
    ->cc(['[email protected]','[email protected]','[email protected]','[email protected]'])
    ->send(new document());

where document is any class that further customizes your email.


You can loop over recipientce like:

foreach (['[email protected]', '[email protected]'] as $recipient) {
    Mail::to($recipient)->send(new OrderShipped($order));
}

See documentation here


it works for me fine, if you a have string, then simply explode it first.

$emails = array();

Mail::send('emails.maintenance',$mail_params, function($message) use ($emails) {
    foreach ($emails as $email) {
        $message->to($email);
    }

    $message->subject('My Email');
});

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to email

Monitoring the Full Disclosure mailinglist require(vendor/autoload.php): failed to open stream Failed to authenticate on SMTP server error using gmail Expected response code 220 but got code "", with message "" in Laravel How to to send mail using gmail in Laravel? Laravel Mail::send() sending to multiple to or bcc addresses Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate How to validate an e-mail address in swift? PHP mail function doesn't complete sending of e-mail How to validate email id in angularJs using ng-pattern

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to laravel-4

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration 'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel Can I do Model->where('id', ARRAY) multiple where conditions? how to fix stream_socket_enable_crypto(): SSL operation failed with code 1 Rollback one specific migration in Laravel How can I resolve "Your requirements could not be resolved to an installable set of packages" error? Define the selected option with the old input in Laravel / Blade Redirect to external URL with return in laravel laravel the requested url was not found on this server