send mail to non-registered user (email list) in a queue

Viewed 575

I am trying to program a Laravel mailing list with a queue Try to send emails to Non-users, I did a good job with registered users and this is my code:

        foreach ($emails as  $i=>$item){
            $user = User::where('email',$item)->first();
            if ($i % $mailsCount == 0)$count++;
            if ($user){
                $thisBody = ElzahabyDynamicLaravelString($user,$body,$this->sign);
                $thisSubject = ElzahabyDynamicLaravelString($user,$subject,$this->sign);
                $when = Carbon::now()->addMinutes($every*$count);
                Mail::to($user)
                    ->later($when,new EmailForQueuing($user,$thisBody,$thisSubject,$request->emailTemplate));
            }
        }

You can notice later() method, which is responsible for the queue. but this only works with Mail::to method which only works for registered users.

So, any idea how to send a mailing list with a queue to non-registered emails.

Thanks in advance.

Edit 1

EmailForQueuing() method is a simple Mailable class

2 Answers

the problem was in the Mail::to() method is that it requires name and email. But I was just sending the email, and I don't have any names!

so what I did is:

make an object includes [emails(required),name(required),any other thing(optional)]

$user = (object)[
    'email' => $email,
    'name' => substr($email, 0, strpos($email, '@')), // here we take the name form email (string before "@")
];

then send it normally:

$when = Carbon::now()->addMinutes($every*$count);
Mail::to($user)->later($when,new EmailForQueuing($user,$thisBody,$thisSubject,$request->emailTemplate));

You may use fill method to create an instance of User without saving into the database it such as;

$mailUser = (new User())->fill(['email' => 'something@foo.bar']);

You may pass also other fields such as ['name' => 'some name', 'age' => 23]

Another option without using the fill would be

$mailUser = (new User(['email' => 'something@foo.bar']))

Your code will be something like this;

$mails = ['email1@com', 'email2@com', 'email3@com', 'etc.com'];
$users = [];

foreach ($mails as $mail) {
    $users[] = (new User(['email' => $mail]));
}

return $users;
Related