在后台发送电子邮件:Laravel 5.4

Send email in background : Laravel 5.4

我正在使用 Laravel 中的内置代码发送电子邮件通知。代码如下。我正在使用 smtp 发送电子邮件

class RegisterNotification extends Notification
{
    use Queueable;

    public function __construct($token)
    {
        $this->token = $token;
    }

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
                ->line('hi');
    }

    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

这里的问题是,完成该过程大约需要 5 秒,并且控制不会返回。我假设如果它返回并在后台执行电子邮件发送工作……那将节省大量时间。

有没有内置的工作可以做同样的事情?我的意思是,控制应该回来,应该说电子邮件已发送……然后它应该在后台完成工作。

控制器中的电子邮件发送代码

class apiRegisterController extends Controller
{
    public function Register(RegisterRequest $request) {

        $RegisterNotification = new RegisterNotification($Token);
        $User->notify($RegisterNotification);
    }
}

队列代码

控制器代码

$job = (new SendForgotPasswordEmail($Data))->onConnection('database');
dispatch($job);

工作

class SendForgotPasswordEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $Data;

    public $tries = 5;

    public function __construct($Data)
    {
        $this->Data = $Data;
    }

    public function handle()
    {
        $Token = $this->Data["Token"];
        $User = $this->Data["User"];
        $RegisterNotification = new RegisterNotification($Token);
        $User->notify($RegisterNotification);
    }
}

您可以使用 laravel 作业队列 https://laravel.com/docs/5.4/queues

Mail::queue(

第 1 步:class RegisterNotification extends Notification 更改为 class RegisterNotification extends Notification implements ShouldQueue

第 2 步:实现队列驱动程序。在你的 config/queue.php 中,确保你的驱动程序没有像这样设置为同步:'default' => env('QUEUE_DRIVER', 'sync'), 并确保你的 .env 没有 QUEUE_DRIVER=sync。您可以查看 Laravel documentation for queues 以选择合适的队列驱动程序

您可以使用 build-in API.

$user = User::findOrFail($id);
Mail::queue('emails.welcome', $data, function ($message) use ($user){
      $message->from('hello@app.com', 'Your Application');

      $message->to($user->email, $user->name)->subject('Your Reminder!');
});

但首先你必须configure the queues

在您的 .env 文件中添加 QUEUE_DRIVER=sync 行,然后在终端 php artisan queue:listen 上写入。

如果您希望队列在服务器上永远 运行,请使用 Supervisor。队列文档解释了如何使用它。