1
votes

I am trying to iterate and send message to mail in array of emails using Laravel Mail::send function

I searched for same problem and found the code below reference from Radmation here https://stackoverflow.com/a/39625789.

$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");
    });

I am wondering the second paramater for iteration usage, so i can message each email with dynamic message of their name.

2

2 Answers

0
votes
$emails = ['[email protected]', '[email protected]'];
foreach($emails as $currentRecipient){
  $customtMsg = //create here a custom msg
  Mail::send(['text' => 'view'], $customtMsg, function ($message) use ($request, $currentRecipient)
    {
        $message->from('[email protected]', 'Joe Smoe');
        $message->to($currentRecipient);
        //Add a subject
        $message->subject("New Email From Your site");
    });
}

Please check usage here

0
votes

You could put emails in associative array, for example:

$emails = [
  '[email protected]' => 'tester', 
  '[email protected]' => 'anotheremail'
];

And then iterate over key=>value pairs, like:

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

If you want to send same mail to multiple recipients at once, you could also pass an array of email=>name pairs to the to method:

$message->to($emails)

But I don't think it is possible to customize an email content individualy with that approach. Also in that case, all of the email addresses are visible to every recipient.