85

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.

2
  • Show more code. Have you tried to insert there existing emails. What failure messages you get? Commented Oct 27, 2014 at 10:19
  • What do you mean by existing emails? I am sending it to valid email addresses if that's what you mean? Will add more code with the failure messages. Thanks.
    – haakym
    Commented Oct 27, 2014 at 10:31

13 Answers 13

143

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) .

7
  • 2
    Thanks for your reply. Apparently I wasn't doing anything wrong, but my IP at work wasn't enabled to relay email outside of our domain! All sorted and working now. Thanks again.
    – haakym
    Commented Oct 27, 2014 at 13:01
  • 14
    @haakym That's why if something doesn't work, you should always try to use the simplest code and make sure it works without a problem. Often problems are not where you expect them to be. Commented Oct 27, 2014 at 13:06
  • 1
    If i want to write somewhere the name of the receipts, how i can do this?
    – Chris P
    Commented Jul 29, 2016 at 13:22
  • this 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 ... i actually will create my answer because it looks messy here. But feel free to add my answer to your accepted answer. My answer: stackoverflow.com/a/39734742/533426
    – Toskan
    Commented Sep 27, 2016 at 21:37
  • Tested in Laravel 5.6, all working. However the array needs to be created, if you are pulling emails data from another table, run a foreach and array_push to a new array.
    – Paddy
    Commented Mar 7, 2019 at 3:47
41

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.

4
  • 2
    Best answer for usage of .env file Commented Oct 30, 2017 at 13:13
  • 26
    You shouldn't reference the ENV directly - use the config helper.
    – voidstate
    Commented Dec 20, 2017 at 15:30
  • 1
    Top answer here.
    – HartleySan
    Commented Apr 14, 2020 at 21:15
  • 1
    There are 2 ways how to achieve to be able to changes email adresses without changing code. You go either with .env file or via Eloquent / table but for the latter you need to think about table structures, so .env is the most simple and straightforward.
    – sba
    Commented Jul 21, 2021 at 9:38
15

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.

14

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.

2
  • it gives me this error: Address in mailbox given [email] does not comply with RFC 2822, 3.6.2. Commented Apr 17, 2020 at 1:43
  • This works with Laravel 8+ too Commented Jul 31, 2022 at 14:35
13

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));
1
  • Thank you for this answer. Saved me a lot of time and grief. Is this change intentional because it seems like too much code for something that should be very short hand. I am defining my to() function using a variable $to = [(object) ['name' => 'Example Name', 'email' => '[email protected]'], (object) ['name' => 'Example Name 2', 'email' => '[email protected]']];
    – Anthony
    Commented Dec 19, 2016 at 3:50
7

You can loop over recipientce like:

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

See documentation here

1
  • I prefer this way as it also works with queue: Mail::to($recipient)->queue(...); Commented Apr 21, 2022 at 19:17
0

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. 😉

1
  • Instead of creating an array element you can just have it as Contacts::pluck('email')->toArray()
    – Kyobul
    Commented Mar 8, 2019 at 14:41
0

Try this:

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

This is what I am doing in one of my multi-vendor e-commerce projects.

$vendorEmails[0]    =    '[email protected]';
    foreach ($this->order->products as $orderProduct){
        $vendorEmails[$count] = \App\User::find($orderProduct->user_id)->email;
        $count++;
    }

    return $this->from('[email protected]', 'Made In India')
        ->to($this->order->billing_email, $this->order->billing_first_name . ' ' . $this->order->billing_last_name)
        ->bcc('[email protected]')
        ->cc($vendorEmails)
        ->subject('Order Placed Successfully - Made In India - ' . $this->order->generated_order_id)
        ->markdown('emails.orderplaced');
}
0

This options works for me when sending dynamic email as a variable

$emails = ['[email protected]', $email];                                                    Mail::send('emails.patchmail', [], function($message) use ($emails)
     {    
     $message->to($emails)->subject('PATCH BIKER REG')->from('[email protected]', 'Patch Global'); });

Also includes the senders email

-1

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");
        });
2
  • 1
    How I can use $message->to($emails); but include the name of the recipents?
    – JCarlosR
    Commented Mar 17, 2017 at 17:07
  • 1
    @JCarlos have the email be the key of the associative array, ['[email protected]' => 'Joe', '[email protected]' => 'Jack']
    – Grant
    Commented Apr 7, 2017 at 8:40
-1

public function sendEmail(Request $request) { $users = User::whereIn("id", $request->ids)->get();

    foreach ($users as $key => $user) {
        Mail::to($user->email)->send(new UserEmail($user));
    }

    return response()->json(['success'=>'Send email successfully.']);
}
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Feb 16, 2023 at 16:58
-15

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');
});
2
  • 3
    This would send N emails to N recipients. The goal is to send 1 email to N recipients.
    – KalC
    Commented Apr 10, 2016 at 4:51
  • ^ for that, use what @Grant mentioned on an answer below, an associative array ['[email protected]' => 'Joe', '[email protected]' => 'Jack']. Commented Nov 21, 2018 at 20:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.