首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

ThinkPHP 整合 PHPMailer 實現郵件發送功能

     編輯:PHP 相關知識

整合步驟

1. 安裝 PHPMailer

推薦使用 Composer (ThinkPHP 5.1+):

composer require phpmailer/phpmailer

或手動下載放入:extend/PHPMailer/

2. 封裝郵件服務類

<?php
// app/common/service/MailService.php
namespace app\common\service;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use think\facade\Config;

class MailService
{
    private $mailer;
    
    public function __construct()
    {
        $this->mailer = new PHPMailer(true);
        $this->initConfig();
    }
    
    private function initConfig()
    {
        $cfg = Config::get('mail');
        $this->mailer->CharSet = 'UTF-8';
        $this->mailer->isSMTP();
        $this->mailer->Host = $cfg['smtp_host'];
        $this->mailer->SMTPAuth = true;
        $this->mailer->Username = $cfg['smtp_user'];
        $this->mailer->Password = $cfg['smtp_pass'];
        $this->mailer->SMTPSecure = $cfg['smtp_secure'] ?? 'tls'; // tls/ssl
        $this->mailer->Port = $cfg['smtp_port'] ?? 587;
        $this->mailer->setFrom($cfg['from_addr'], $cfg['from_name']);
    }
    
    public function send(string $to, string $subject, string $body, array $attachments = []): bool
    {
        try {
            $this->mailer->clearAddresses();
            $this->mailer->addAddress($to);
            $this->mailer->Subject = $subject;
            $this->mailer->Body = $body;
            $this->mailer->isHTML(true);
            
            foreach ($attachments as $path => $name) {
                $this->mailer->addAttachment($path, $name);
            }
            
            return $this->mailer->send();
        } catch (Exception $e) {
            // 記錄日誌
            \think\facade\Log::error("Mail send failed: {$this->mailer->ErrorInfo}");
            return false;
        }
    }
}

3. 配置文件

<?php
// config/mail.php
return [
    'smtp_host' => 'smtp.exmail.qq.com',
    'smtp_user' => 'noreply@example.com',
    'smtp_pass' => 'your_password',
    'smtp_secure' => 'ssl',
    'smtp_port' => 465,
    'from_addr' => 'noreply@example.com',
    'from_name' => '系統通知',
];

4. 控制器調用

<?php
// app/controller/Index.php
namespace app\controller;

use app\common\service\MailService;
use think\facade\View;

class Index
{
    public function testMail()
    {
        $mail = new MailService();
        $result = $mail->send(
            'user@example.com',
            '測試郵件',
            '

Hello ThinkPHP!

這是一封測試郵件。

' ); return json(['success' => $result, 'message' => $result ? '發送成功' : '發送失敗']); } }

5. 進階功能

  • 佇列異步發送:結合 ThinkPHP Queue,MailJob 推入 Redis/RabbitMQ
  • 模板引擎:使用 View::fetch('mail/welcome', ['user' => $user]) 渲染 HTML
  • 批次發送:addBCC() 隱藏副本,保護收件人隱私
  • 內嵌圖片:addEmbeddedImage($path, 'cid'),HTML 中用

常見問題排查

現象可能原因解決
SMTP connect() failed端口/加密方式錯誤檢查 465(SSL)/587(TLS)、防火牆
Authentication failed帳號密碼/授權碼錯誤確認 SMTP 服務商授權碼 (非登入密碼)
郵件進垃圾箱SPF/DKIM/DMARC 未配置域名 DNS 配置郵件認證記錄
中文亂碼CharSet 未設定$mail->CharSet = 'UTF-8'

封裝服務類統一管理配置與異常,讓控制器保持輕量,符合單一職責原則。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved