0
点赞
收藏
分享

微信扫一扫

Laravel使用队列后台发送邮件

Alex富贵 2023-02-09 阅读 97


使用Redis队列方式

​textlaravel.cc\laravel5\config\queue.php​

修改为Redis队列方式
​​​'default' => env('QUEUE_CONNECTION', 'redis'),​

Laravel使用队列后台发送邮件_App


在没有开启队列监听,或者处理第一个队列任务命令,那么队列任务是不会执行的。

// 开启队列监听器
php artisan queue:listen
// 只处理第一个队列任务
php artisan queue:work

1 创建一个job

​php artisan make:job SendEmail​

然后在​​app/jobs​​目录下就有一个类了,该类有一个handle方法,该方法就是具体要在队列中处理的任务逻辑。

<?php

namespace App\Jobs;

use App\Mail\SendReportReply;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;


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

protected $user;
# 实例化
public function __construct(User $user)
{
$this->user = $user;
}

# 执行队列的方法 比如发送邮件
public function handle()
{
$user = $this->user;
# laravel自带Mail类所以直接用就好了
\Mail::send('email.test',['name'=>'textname'],function($message){
$to = '2624466181@qq.com';
$message ->to($to)->subject('测试邮件');
});

echo $user->name;

}
}

Mail::send 需要传递三个参数

  • 第一个是邮件视图
  • 第二个是传入视图的数据
  • 第三个是一个闭包,该闭包中定义了收件人、抄送人(如果有的话)、邮件主题、附件等信息。

修改 queue 相关代码后,必须要使用 php artisan queue:restart 来重启队列服务,否则所做的修改可能不会生效(没法重现了,按理说应该和使用 queue:listen 或 queue:work 有关,不过最好还是重启;可能和 supervisor 开启多个 queue:work 进程也有关系,本地测试的时候只有一个进程)。

Laravel使用队列后台发送邮件_php_02


Laravel使用队列后台发送邮件_App_03

2 邮件模版

Laravel使用队列后台发送邮件_laravel_04

3 控制器路由

<?php

namespace App\Http\Controllers\Text;

use App\Http\Controllers\Controller;
use App\Jobs\SendEmail;
use App\User;
use Illuminate\Http\Request;

class EmailTextController extends Controller
{
public function emailtxt()
{
// \Mail::send('email.test',['name'=>'textname'],function($message){
// $to = '2624466181@qq.com';
// $message ->to($to)->subject('测试邮件');
// });

$user = User::find(1);
// $this->dispatch(new SendEmail($user));

dispatch(new SendEmail($user));
echo "SendEmail";
}
}

// 这个任务将被分发到默认队列...
Job::dispatch();

// 这个任务将被发送到「emails」队列...
Job::dispatch()->onQueue('emails');

路由

​Route::get('emailtxt', 'Text\EmailTextController@emailtxt');​

Laravel使用队列后台发送邮件_App_05


Laravel使用队列后台发送邮件_App_06


举报

相关推荐

0 条评论