0

I want to send emails to all of the users in my application. I created a separate sample project where the only function is one to add/create new users together with their email and name. I want to email each of my existing users whenever there is a new one who signed up. Like a "Hello, we have a new member!" message.

Controller

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

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

    return redirect('/customers');
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
Brent Cruz
  • 29
  • 4
  • I would recommend you to create a job, this job is tve responsible for sending an email to the desired user. Why use this ? If you have 10k users or more, you have to call the mail function here, and if anything happens, it stops you don't know where, but wit a job, you can retry the job – matiaslauriti Jul 04 '21 at 16:24
  • 3
    Please use some service to send bulk emails. Using PHP scripts to send bulk emails is highly discouraged, especially for it's time limitations and [other factors mentioned here](https://stackoverflow.com/questions/1118154/sending-mass-email-using-php). Mailchimp looks fine https://mailchimp.com/ – nice_dev Jul 04 '21 at 16:25

1 Answers1

0

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

Kaushal Joshi
  • 23
  • 1
  • 9