Laravel SMTP邮件发送配置与命令测试
本实例详细解析如何在Laravel框架中集成SMTP服务以完成邮件发送任务,提供具体配置步骤供开发者参考实践。
第一步,修改项目根目录下的.env配置文件。
需设定以下关键参数:MAIL_DRIVER指定为smtp;MAIL_HOST填入邮箱服务商的SMTP主机地址(如smtp.后缀);MAIL_PORT配置邮件服务器的端口号;MAIL_USERNAME填写发件人的完整邮箱地址;MAIL_PASSWORD使用邮箱生成的第三方授权码或专用密码;MAIL_FROM_ADDRESS定义发件邮箱地址;MAIL_FROM_NAME设置发件人显示名称。
第二步,检查config目录下的mail.php文件。
通常情况下无需手动修改此文件,因为.env中的配置优先级更高,会自动覆盖该文件中的默认值。仅在.env缺失相应配置时,系统才会回退读取mail.php中的内容。
第三步,编写位于app/console/commands/sendMail.php的自定义命令类。
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
class SendMailCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'demo:SendMail';
/**
* The console command description.
*
* @var string
*/
protected $description = '测试脚本SendMail';
/**
* constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$content = '这是一封的测试邮件.';
$toMail = '目标邮箱';
Mail::raw($content, function ($message) use ($toMail) {
$message->subject('[ 测试 ] 测试邮件SendMail - ' .date('Y-m-d H:i:s'));
$message->to($toMail);
});
}
}
第四步,进行功能测试。
打开终端,切换至项目根目录路径下,准备执行相关指令。
php artisan demo:SendMail
期望上述内容能为基于Laravel框架的PHP开发人员在邮件模块实现上提供帮助。