当前位置 主页 > 网站技术 > 代码类 >

    laravel5.6 框架邮件队列database驱动简单demo示例

    栏目:代码类 时间:2020-01-26 15:09

    本文实例讲述了laravel5.6 框架邮件队列database驱动。分享给大家供大家参考,具体如下:

    一: 邮件初始参数配置

    配置 .env  (demo示例是163邮箱,开启POP3和SMTP服务,获取授权密码)

    MAIL_DRIVER=smtp
    MAIL_HOST=smtp.163.com
    MAIL_PORT=465
    MAIL_USERNAME=你的163邮箱地址
    MAIL_PASSWORD=你的163邮箱地址对应的授权密码(不是登录密码)
    MAIL_ENCRYPTION=ssl
    MAIL_FROM_ADDRESS=你的163邮箱地址
    
    

    修改 .env 中的 QUEUE_DRIVER 值   (配置文件 config/queue.php  默认是同步'sync', demo配置'database'驱动)

    QUEUE_DRIVER=database
    
    

    二: 数据库建表

    //队列任务表
    php artisan queue:table
    //任务执行失败表
    php artisan queue:failed-table
    //执行数据库迁移
    php artisan migrate
    
    

    三: 生成任务类

    php artisan make:job SendEmail
    
    

    生成之后,在handle方法中处理发送队列邮件

    <?php
    namespace App\Jobs;
    use Illuminate\Bus\Queueable;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Foundation\Bus\Dispatchable;
    use Illuminate\Support\Facades\Mail;
    class SendEmail implements ShouldQueue
    {
      use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
      private $email;
      private $content;
      private $subject;
      /**
       * Create a new job instance.
       *
       * @return void
       */
      public function __construct( $email, $content, $subject)
      {
        $this->email = $email;
        $this->content = $content;
        $this->subject = $subject;
      }
      /**
       * Execute the job.
       *
       * @return void
       */
      public function handle()
      {
        $email = $this->email;
        $subject = $this->subject;
        Mail::send(
          'admin.emails.test',
          ['content' => $this->content],
          function ($message) use($email, $subject) {
            $message->to($email)->subject($subject);
          }
        );
        // Mail::failures() 返回的错误邮件信息,判断是否发送成功. (无错误信息,返回空数组)
        if(empty(Mail::failures())){
          dd('发送成功');
        }else{
          dd('发送失败');
        }
      }
    }
    
    

    四: 对应邮件发送的控制器,任务加到队列中

    <?php
    namespace App\Http\Controllers\Admin;
    use App\Http\Controllers\Controller;
    use App\Jobs\SendEmail;
    /**
     * Description of BookedController
     */
    class BookedController extends Controller {
      public function queueSend()
      {
        //邮件发送demo数据
        $data =[
          0=>[
            'email'=>'XXXXXX@qq.com',
            'content'=>'Hello World One',
            'subject'=>'测试标题一',
          ],
          1=>[
            'email'=>'XXXXXX@qq.com',
            'content'=>'Hello World Two',
            'subject'=>'测试标题二',
          ]
        ];
        foreach ($data as $item){
          //数据循环,插入表jobs中,队列初始化数据
          dispatch(new SendEmail($item['email'],$item['content'],$item['subject']));
        }
      }
    }
    
    

    五:  执行队列里的任务