- 安装composer包
composer require guzzlehttp/guzzle
- 配置env文件
MAIL_DRIVER=smtp
MAIL_HOST=smtp.qq.com
MAIL_PORT=465
MAIL_USERNAME=XXXXXXXXX@qq.com
MAIL_PASSWORD=XXXXXXXXXX //非邮箱密码,需要单独开启
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=XXXXXXXXX@qq.com
MAIL_FROM_NAME=这写项目名称
- MAIL_PASSWORD获取
- 创建php文件,app/Mail/Register.php
<?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 = 'email.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);
}
}
- 创建服务
<?php
namespace App\Services\Mail;
use App\Helpers\Traits\SingletonTrait;
use App\Mail\Register;
use Illuminate\Support\Facades\Mail;
class SendMailService
{
//单例
use SingletonTrait;
public function __construct(){
}
public function register(){
$subject = "欢迎注册!";
$to = 'XXXXXX@qq.com';//发送到该邮箱
$viewData = [
'title' => $subject,
'code' => mt_rand(1000, 9999),
'url' => 'https://www.baidu.com',
];
$register = new Register($subject, $viewData);
return Mail::to($to)->send($register);
}
}
- Controller
public function register(){
SendMailService::getInstance()->register();
}
- 创建view模版,resources/views/email/register.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用户注册</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@200;600&display=swap" rel="stylesheet">
<!-- Styles -->
</head>
<body>
<div class="flex-center position-ref full-height">
<div class="content">
<div class="title m-b-md">
这是标题
</div>
<div class="title m-b-md">
这是内容
</div>
</div>
</div>
</body>
</html>
- 队列
php artisan queue:work
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END