laravel郵件發送小例子(自記)

一、app裏面建立Mail文件夾:

clipboard.png
裏面編寫register文件:php

<?php

namespace App\Mail;

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

class Register extends Mailable
{
    use Queueable, SerializesModels;

    public $user;

    public $subject = '註冊郵件';

    /**
     * Create a new message instance.
     * user並不是強制的。若本身模擬能夠把User限制去掉
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

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

二、郵件html模板:

在views裏面的email裏面編寫register.blade.phphtml

三、編寫mailController

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Mail;
use App\Mail\Register;

class MailController extends Controller
{
    public function sendtest(){
        //因爲我這裏模擬用戶註冊發送郵件,用內置類。
        $user = new \stdclass;
        $user->name='hello world';
        Mail::to('XXX@qq.com')
            ->queue(new Register($user));
        echo 'success';
    }
}

四、開啓隊列

php artisan queue:workapp

五、配置env

MAIL_DRIVER=smtp
MAIL_HOST=smtp.163.com
MAIL_PORT=465
MAIL_USERNAME=name@163.com
MAIL_PASSWORD=password
MAIL_FROM_ADDRESS=name@163.com
MAIL_FROM_NAME=learn(可自定義)
MAIL_ENCRYPTION=ssl

六、添加路由運行便可

相關文章
相關標籤/搜索