ThinkPHP + PHPMailer实现发邮件功能
申明:请确保你已经获得 邮箱的授权码(SMTP)
1、打开ThinkPHP框架的项目终端,进入项目根目录;
2、执行以下命令安装PHPMailer;
composer require phpmailer/phpmailer
3、等待安装完成后,在 vendor 目录下会出现 phpmailer 文件夹,表示 PHPMailer 库已经安装成功;
4、在config/mail.php
文件中进行配置:
return [ // 邮箱服务器地址 'host' => 'smtp.qq.com', // 邮箱服务器端口号 'port' => 465, // 邮箱账号 'username' => **********', // 邮箱密码或授权码 'password' => 'your_password', // 是否使用ssl加密 'secure' => 'ssl', // 发件人邮箱地址 'from' => [ 'address' => **********', 'name' => 'Your Name', ], ];
5、创建一个邮件发送类,可以在 app/libraries/Mail.php
文件中创建:
<?php namespace app\libraries; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; class Mail { protected $mailer; public function __construct() { $this->mailer = new PHPMailer(true); // 邮箱服务器配置 $this->mailer->isSMTP(); $this->mailer->Host = config('mail.host'); $this->mailer->Port = config('mail.port'); $this->mailer->SMTPAuth = true; $this->mailer->Username = config('mail.username'); $this->mailer->Password = config('mail.password'); $this->mailer->SMTPSecure = config('mail.secure'); // 发件人信息 $this->mailer->setFrom(config('mail.from.address'), config('mail.from.name')); } public function send($to, $subject, $body) { try { // 收件人信息 $this->mailer->addAddress($to); // 邮件主题和内容 $this->mailer->Subject = $subject; $this->mailer->Body = $body; // 发送邮件 $this->mailer->send(); return true; } catch (Exception $e) { return false; } } }
6、在控制器中调用邮件发送类即可:
<?php namespace app\controller; use app\libraries\Mail; class Index { public function sendMail() { $mail = new Mail(); $to = 'recipient@example.com'; $subject = 'Test Email'; $body = 'This is a test email.'; if ($mail->send($to, $subject, $body)) { echo 'Email sent successfully.'; } else { echo 'Failed to send email.'; } } }