Laravel 傳送郵件

expectedSelf發表於2019-11-11

安裝 Guzzle HTTP 函式庫

composer require guzzlehttp/guzzle

郵箱配置

MAIL_DRIVER=smtp
MAIL_HOST=smtp.qq.com
MAIL_PORT=25
MAIL_FROM_ADDRESS=xxx@qq.com  
MAIL_FROM_NAME="發件人"  
MAIL_USERNAME=xxx@qq.com   
MAIL_PASSWORD=******   #SMTP授權密碼

生成 Mailable 物件

php artisan make:mail Register

內容可以如下修改,放入佇列,配置佇列

<?php

namespace App\Mail;

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

class Register extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    public $view = 'emails.register';

    public $subject = '歡迎註冊';

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($subject, $viewData = [], $view = '')
    {
        if(!empty($subject)){
            $this->subject($subject);
        }

        if(!empty($view)){
            $this->view = $view;
        }

        if(! view()->exists($this->view)){
            abort(404, '註冊郵件模板不存在');
        }

        if(!empty($viewData)){
            $this->with($viewData);
        }
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->markdown($this->view);
    }
}

呼叫

class TestController extends Controller
{
    public function sendEmail(){
        $to = 'xxx@qq.com';
        $subject = '郵件主題';
        $viewData = [
            'code' => mt_rand(1000, 9999),
            //...
        ];
        return Mail::to($to)->send(new Register($subject, $viewData));
    }
}
php artisan queue:work
本作品採用《CC 協議》,轉載必須註明作者和本文連結
所幸無礙

相關文章