使用Larvael中的队列发送邮件

时间:2018-05-30 14:37:40

标签: php laravel

第一次在laravel中使用队列我有一个简单的联系表单页面,用户提交信息,我正在尝试使用队列来接收该信息。我很确定我的设置不正确,因为当我运行队列时它说处理。我的问题是我的数据是如何发送的以及在数组中发送数据的正确方法。

AskEmailController.php

<?php

namespace App\Http\Controllers;
use App\Jobs\HelpEmailJob;
use Illuminate\Support\Facades\Mail;
use Illuminate\Http\Request;
use Carbon\Carbon;
class AskEmailController extends Controller
{

    public function askemail()
    {
        return view('help.question');
    }
    public function store(Request $request)
    {



                  HelpEmailJob::dispatch()
                 ->delay(Carbon::now()->addSeconds(5));
    }

}

HelpEmailJob     

namespace App\Jobs;
use App\Mail\HelpEmailMailable;
use Illuminate\Support\Facades\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

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

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

    Mail::to('mikeshasaco@gmail.com')->queue(new HelpEmailMailable());
    }
}

HelpEmailMailiable

<?php

namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class HelpEmailMailable extends Mailable
{
    use Queueable, SerializesModels;
    protected $data;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->$data = $data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {

            $data = array(
                'sirname' => $this->data['sirname'],
                'email' => $this->data['email'],
                'bodymessage' => $this->data['bodymessage'],
            );
        return $this->view('help.contactinfo')
        ->with([
            'data' =>$data,
        ]);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以直接从控制器发送邮件,如下所示:

class AskEmailController extends Controller
{
    public function store(Request $request)
    {
        Mail::to('mikeshasaco@gmail.com')->send(new HelpEmailMailable);
    }
}

而不是使用工作。默认情况下,通过实现ShouldQueue界面来制作电子邮件队列:

class HelpEmailMailable extends Mailable implements ShouldQueue
{
  ...
}

在测试时确保您的队列正在运行,并在您对代码进行更改后始终重新启动它。