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 协议》,转载必须注明作者和本文链接
所幸无碍
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!