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.';
        }
    }
}

全部评论

相关推荐

06-04 09:27
门头沟学院 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-24 13:40
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务