How to pass multiple email in laravel mail
In Laravel, you can pass multiple emails to the to
method of the Mail
facade or the Illuminate\Mail\Message
class. Here are a few ways to do it:
Method 1: Using an array of email addresses
use Illuminate\Support\Facades\Mail;
Mail::to(['[email protected]', '[email protected]', '[email protected]'])->send(new MyMail());
In this example, MyMail
is a mail class that extends Illuminate\Mail\Mailable
. You can pass an array of email addresses to the to
method, and Laravel will send the email to all the addresses in the array.
Method 2: Using a collection of email addresses
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Collection;
$emails = collect(['[email protected]', '[email protected]', '[email protected]']);
Mail::to($emails)->send(new MyMail());
In this example, we create a collection of email addresses using the collect
method, and then pass it to the to
method.
Method 3: Using a loop to send emails to multiple recipients
use Illuminate\Support\Facades\Mail;
foreach (['[email protected]', '[email protected]', '[email protected]'] as $email) {
Mail::to($email)->send(new MyMail());
}
In this example, we use a loop to iterate over an array of email addresses and send a separate email to each recipient.
Method 4: Using a custom method to send emails to multiple recipients
use Illuminate\Support\Facades\Mail;
public function sendEmails(array $emails)
{
foreach ($emails as $email) {
Mail::to($email)->send(new MyMail());
}
}
$emails = ['[email protected]', '[email protected]', '[email protected]'];
sendEmails($emails);
In this example, we define a custom method sendEmails
that takes an array of email addresses as an argument. We then use a loop to iterate over the array and send a separate email to each recipient.
Note that in all cases, you need to make sure that the email addresses are valid and that the mail server is configured correctly to send emails to multiple recipients.