Utilizing Laravel Mailable to Send Multiple Emails

Using queue emails instead of sending messages immediately is beneficial because it allows the main process supporting the request to continue without waiting for the email sending process. In my case, I’m utilizing Laravel 5.6 to send emails to multiple email addresses.


Question:

I am utilizing
laravel 5.6
and attempting to send to multiple email addresses. Currently, my code only functions for one email. How can I modify it to accommodate multiple emails? I am employing
mailable
.

Here is my controller

public function sendEmail(Request $request)
{
    Mail::send(new sendMail());
    Session::flash('conf_email', 'ok');
    return redirect('/send-email');
}
class SendMail extends Mailable
{
    public function build(Request $request)
    {
        return $this->view('mail', ['msg' => $request->message])->to($request->to);
    }
}


Solution 1:

The to() function can take in an array of emails (as strings or objects). For additional details, please refer to the following link: https://laravel.com/api/5.5/Illuminate/Contracts/Mail/Mailer.html#method_to.

so you can do something like this

class SendMail extends Mailable
{
   public function build(Request $request)
   {
     $users=User::all();
     return $this->view('mail', ['msg' => $request->message])->to($users);
     //or 
      return $this->view('mail', ['msg' => $request->message])->to(['[email protected]','[email protected]']);
    }
}


Solution 2:

You just need to change sendEmail function to:
public function sendEmail(Request $request)
{
    Mail::to(['[email protected]','[email protected]'])->send(new sendMail()); 
    Session::flash('conf_email', 'ok');
    return redirect('/send-email');
}

Frequently Asked Questions