# Composer (推薦)
composer require phpmailer/phpmailer
# 或手動下載:https://github.com/PHPMailer/PHPMailer
方案 A:本地 Sendmail/Postfix(簡單但送達率低)
# Ubuntu/Debian
sudo apt-get install postfix
sudo systemctl enable postfix
sudo systemctl start postfix
# php.ini
sendmail_path = /usr/sbin/sendmail -t -i
方案 B:SMTP 服務商(推薦:SendGrid、Mailgun、阿里雲郵件、騰訊雲郵件)
<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
/**
* 發送郵件統一入口
* @param string|array $to 收件人,單個或數組
* @param string $subject 主題
* @param string $body HTML 內容
* @param array $attachments 附件 ['path'=>'', 'name'=>'', 'type'=>'']
* @param array $options 額外選項
* @return bool|array 成功返回 true,失敗返回 ['error'=>...]
*/
function sendMail($to, $subject, $body, array $attachments = [], array $options = []) {
$mail = new PHPMailer(true); // true = 拋出異常
try {
// === 基礎配置 ===
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
// === 發送模式選擇 ===
$useSmtp = $options['smtp'] ?? true;
if ($useSmtp) {
// SMTP 模式(生產推薦)
$mail->isSMTP();
$mail->Host = $options['smtp_host'] ?? 'smtp.example.com';
$mail->Port = $options['smtp_port'] ?? 587; // 587 TLS, 465 SSL
$mail->SMTPSecure = $options['smtp_secure'] ?? PHPMailer::ENCRYPTION_STARTTLS; // TLS
$mail->SMTPAuth = true;
$mail->Username = $options['smtp_user'] ?? 'user@example.com';
$mail->Password = $options['smtp_pass'] ?? 'password';
// $mail->SMTPDebug = SMTP::DEBUG_SERVER; // 調試輸出
} else {
// mail() 函數模式(簡單但不可靠)
$mail->isMail();
}
// === 發件人 ===
$mail->setFrom(
$options['from_email'] ?? 'noreply@example.com',
$options['from_name'] ?? '系統通知'
);
$mail->addReplyTo($options['reply_to'] ?? $options['from_email'] ?? 'noreply@example.com');
// === 收件人 ===
$recipients = is_array($to) ? $to : [$to];
foreach ($recipients as $rcpt) {
if (is_array($rcpt)) {
$mail->addAddress($rcpt[0], $rcpt[1] ?? '');
} else {
$mail->addAddress($rcpt);
}
}
// === 抄送/密送 ===
if (!empty($options['cc'])) {
foreach ((array)$options['cc'] as $cc) $mail->addCC($cc[0] ?? $cc, $cc[1] ?? '');
}
if (!empty($options['bcc'])) {
foreach ((array)$options['bcc'] as $bcc) $mail->addBCC($bcc[0] ?? $bcc, $bcc[1] ?? '');
}
// === 內容 ===
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = $options['alt_body'] ?? strip_tags($body); // 純文本備選
// === 附件 ===
foreach ($attachments as $att) {
$path = $att['path'] ?? $att;
$name = $att['name'] ?? basename($path);
$encoding = $att['encoding'] ?? 'base64';
$type = $att['type'] ?? 'application/octet-stream';
if (file_exists($path)) {
$mail->addAttachment($path, $name, $encoding, $type);
} else {
error_log("郵件附件不存在: $path");
}
}
// === 發送 ===
$mail->send();
return true;
} catch (Exception $e) {
error_log("PHPMailer 錯誤: {$mail->ErrorInfo}");
return ['error' => $mail->ErrorInfo, 'code' => $mail->getErrorCode()];
}
}
?>
<?php
$result = sendMail(
'user@example.com',
'歡迎註冊',
'<h1>歡迎</h1><p>感謝註冊,您的驗證碼:<strong>123456</strong></p>'
);
if ($result === true) echo "發送成功";
else echo "失敗: " . $result['error'];
?>
<?php
$attachments = [
['path' => '/data/reports/monthly.pdf', 'name' => '月報.pdf'],
['path' => '/data/images/chart.png', 'name' => '圖表.png', 'type' => 'image/png'],
];
sendMail('boss@company.com', '月度報告', '請查收附件', $attachments);
<?php
function sendBatch(array $recipients, $subject, $body, array $attachments = []) {
$mail = new PHPMailer(true);
// ... 配置 SMTP、發件人等(同上,不重複) ...
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
foreach ($attachments as $att) {
$mail->addAttachment($att['path'], $att['name'] ?? '');
}
$results = [];
foreach ($recipients as $to) {
// 清除上一輪收件人
$mail->clearAddresses();
$mail->addAddress($to['email'], $to['name'] ?? '');
try {
$mail->send();
$results[$to['email']] = true;
} catch (Exception $e) {
$results[$to['email']] = $mail->ErrorInfo;
// 記錄失敗,繼續發送下一個
}
}
return $results;
}
?>
| 錯誤現象 | 可能原因 | 解決方案 |
|---|---|---|
| SMTP connect() failed | 端口阻塞、主機錯誤、防火牆 | telnet 檢查端口、檢查安全組、嘗試 465/587/2525 |
| Authentication failed | 用戶名/密碼錯誤、需授權碼 | 確認 SMTP 密碼/授權碼、開啟「客戶端授權」 |
| Certificate verification failed | 自簽證書、CA 不信任 | $mail->SMTPOptions = ['ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]] (僅測試) |
| 郵件進垃圾箱 | 無 SPF/DKIM/DMARC、內容觸發規則 | 配置域名記錄、優化內容、使用專業服務商 |
| 中文亂碼 | CharSet 未設置、編碼不匹配 | $mail->CharSet = 'UTF-8'; $mail->Encoding = 'base64'; |
| 大附件發送失敗 | post_max_size/upload_max_filesize/memory_limit | 調整 php.ini、分片上傳、雲存儲鏈接代替附件 |
// 生產者
Redis::lpush('mail_queue', json_encode(['to'=>..., 'subject'=>..., 'body'=>...]));
// 消費者
while (true) {
$task = Redis::rpop('mail_queue');
if ($task) sendMail(...json_decode($task, true)...);
usleep(100000);
}
allow_url_include、disable_functions 包含 mail 相關危險函數PHPMailer 是 PHP 郵件發送的事實標準,配合 SMTP 服務商、異步隊列、模版引擎,能構建企業級可靠郵件系統。