Laravel 发送邮件

安装 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 协议》,转载必须注明作者和本文链接

所幸无碍

讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!