首页 > 解决方案 > 如何向 Laravel 中的所有用户发送电子邮件?

问题描述

我想向我的应用程序中的所有用户发送电子邮件。我创建了一个单独的示例项目,其中唯一的功能是添加/创建新用户及其电子邮件和姓名。每当有新用户注册时,我想给我的每个现有用户发送电子邮件。就像“你好,我们有一个新成员!” 信息。

控制器

public function store()
{
    $customer = Customer::create($this->validatedData());

    foreach ($customer as $customers) {
        Mail::to($customers->email)->send(new WelcomeMail());
    }

    return redirect('/customers');
}

标签: phplaravellaravel-mail

解决方案


Here your code is correct but not completely

So I have modified it

Now you need to create one Job file using

php artisan make:job WelcomeMessage and then run

 php artisan migrate

to send the mail

use App\Job\WelcomeMessage;

public function store()
{

$customer = Customer::create($this->validatedData());

if ($customer) {
    $allUser = Customer::where('id', '!=', $customer->id)->get();

    $html = "Your html file with mail content";
    $sub  = "Welcome Mail";

    foreach($allUser as $allUsers){

     Mail::to($allUsers->email)->send(new WelcomeMessage($html,$sub));

    }
}


return redirect('/customers');

}

If you run this command php artisan make:job WelcomeMessage then it will create the page in the app\Job folder. Then paste the below code on that page.

<?php

namespace App\Emails;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class UserVerificationMail extends Mailable
{

    use Queueable, SerializesModels;
    public $subject;
    public $file;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($file,$subject)
    {
        $this->subject  = $subject;
        $this->file     = $file;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
      return $this->from(env('MAIL_FROM_ADDRESS'), env('APP_NAME'))
        ->subject($this->subject)
        ->markdown($this->file);
    }
}

and then run php artisan queue:listen

This will work

Thank You


推荐阅读