简体   繁体   中英

How can I iterate the message of a Mail::send Laravel function?

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 = ['tester@blahdomain.com', 'anotheremail@blahdomian.com'];
    Mail::send('emails.lead', ['name' => $name, 'email' => $email, 
     'phone' => $phone], function ($message) use ($request, $emails)
    {
        $message->from('no-reply@yourdomain.com', '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.

You could put emails in associative array, for example:

$emails = [
  'tester@blahdomain.com' => 'tester', 
  'anotheremail@blahdomian.com' => '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('no-reply@yourdomain.com', '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.

$emails = ['tester@blahdomain.com', 'anotheremail@blahdomian.com'];
foreach($emails as $currentRecipient){
  $customtMsg = //create here a custom msg
  Mail::send(['text' => 'view'], $customtMsg, function ($message) use ($request, $currentRecipient)
    {
        $message->from('no-reply@yourdomain.com', 'Joe Smoe');
        $message->to($currentRecipient);
        //Add a subject
        $message->subject("New Email From Your site");
    });
}

Please check usage here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM