How to send dynamic email to multiple users(email addresses) from database table in Laravel?

时间:2019-04-17 02:11:38

标签: laravel laravel-5

Is anyone can suggest what is the best way or how can I send email to all the users that are located in my news_subscibers table with dynamic data from a form? I tried and was a able to send email to a hard coded email.

 public function sendNewsEmail(Request $request)
{
    $this->validate($request,[
      'subject' => 'bail|string|required|string|max:100',
      'bodymessage' => 'bail|string|required|string|min:10',
    ]);

    $data = array(
      'subject' => $request->subject,
      'bodymessage' => $request->bodymessage
    );


    $subscriber_emails = NewsSubscriber::pluck('subs_email')->toArray();

    foreach ($subscriber_emails as $mail)
    {
    Mail::send('email.news-email', $data, $mail,  function($message) use ($data, $mail){
          $message->from('not_reply@sik.org');
          $message->to('abc@gmail.com');
          $message->cc($mail);
          $message->subject($data['subject']);
      });

      Session::flash('success', 'Your message was sent!');
      return redirect()->back();

    };


}

I would like to send the email to all users in news_subscribers table.

3 个答案:

答案 0 :(得分:0)

You have your success flash message and returned response inside of your $subscriber_emails loop. This causes only the first email to send, then the loop stops and returns the redirect response.

Place those lines after to keep the loop going for all emails.

public function sendNewsEmail(Request $request)
{
    // ...


    $subscriber_emails = NewsSubscriber::pluck('subs_email')->toArray();

    foreach ($subscriber_emails as $mail)
    {
        Mail::send('email.news-email', $data, $mail, function ($message) use ($data, $mail) {
            $message->from('not_reply@sik.org');
            $message->to('abc@gmail.com');
            $message->cc($mail);
            $message->subject($data['subject']);
        });
    }

    Session::flash('success', 'Your message was sent!');

    return redirect()->back();
}

(Assuming this is your issue. If not, you should add any error messages or unexpected behavior you're experiencing.)

答案 1 :(得分:0)

您只需在$message->to($subscriber_emails)中传递数组,无需foreach循环即可将电子邮件发送给多个用户

Mail::send('email.news-email', $data, $mail,  function($message) use ($data, $subscriber_emails){
      $message->from('not_reply@sik.org');
      $message->to($subscriber_emails);
      $message->subject($data['subject']);
  });

答案 2 :(得分:0)

您可以使用mailable发送多封电子邮件

生成新的可邮寄邮件

php artisan make:mail SampleMail

此命令将在app/mail/SampleMail.php中生成一个文件 可选在可邮寄类中编写一些逻辑

使用

在控制器中可邮寄呼叫
$user = User::get(); // fetch user's to send mails
Mail::to($user)->send(new SampleMail()); 

可邮寄文档-https://laravel.com/docs/5.8/mail#generating-mailables