PHP 發送郵件歷經三個時代:早期依賴系統 sendmail 的 mail() 函數;中期興起 SMTP 協議直連與 PHPMailer 等庫;現代則推薦使用 API 服務。本文系統梳理各方案優劣,助你選型。
<?php
$to = 'user@example.com';
$subject = '測試郵件';
$message = '這是使用 mail() 發送的郵件';
$headers = 'From: noreply@example.com' . "\r\n" .
'Reply-To: support@example.com' . "\r\n" .
'Content-Type: text/html; charset=UTF-8' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
缺點:依賴伺服器 sendmail/postfix 配置、無 SMTP 驗證、易進垃圾箱、不支援 SSL/TLS、無附件/HTML 完善支援、難以除錯。
<?php
$this->load->library('email');
$config = [
'protocol' => 'smtp',
'smtp_host' => 'smtp.163.com',
'smtp_port' => 465, // SSL 埠
'smtp_user' => 'your@163.com',
'smtp_pass' => 'auth_code', // 授權碼而非登入密碼
'smtp_crypto' => 'ssl', // 或 'tls' (port 587)
'mailtype' => 'html',
'charset' => 'utf-8',
'wordwrap' => true,
'priority' => 3,
'crlf' => "\r\n",
'newline' => "\r\n",
];
$this->email->initialize($config);
$this->email->from('your@163.com', '系統通知');
$this->email->to('target@example.com');
$this->email->subject('測試標題');
$this->email->message('<h1>HTML 內容</h1><p>支援中文</p>');
$this->email->attach('/path/to/file.pdf');
if ($this->email->send()) {
echo '發送成功';
} else {
show_error($this->email->print_debugger());
}
?>
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// 伺服器設定
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@gmail.com';
$mail->Password = 'app_password'; // Gmail 需應用程式密碼
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // SSL
$mail->Port = 465;
$mail->CharSet = 'UTF-8';
$mail->Timeout = 30;
// 發件人/收件人
$mail->setFrom('your@gmail.com', '系統名稱');
$mail->addAddress('user@example.com', '收件人姓名');
$mail->addReplyTo('support@example.com', '客服');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');
// 附件
$mail->addAttachment('/path/to/file.pdf', 'rename.pdf');
$mail->addStringAttachment($pdfContent, 'dynamic.pdf');
// 內容
$mail->isHTML(true);
$mail->Subject = 'PHPMailer 測試';
$mail->Body = '<h1>你好</h1><p>這是 <b>HTML</b> 郵件</p>';
$mail->AltBody = '純文字備用內容';
$mail->send();
echo '郵件已發送';
} catch (Exception $e) {
echo "發送失敗: {$mail->ErrorInfo}";
}
?>
| 服務商 | SMTP 主機 | SSL 埠 | TLS 埠 | 備註 |
|---|---|---|---|---|
| Gmail | smtp.gmail.com | 465 | 587 | 需開啟「低安全性應用」或使用應用程式密碼 |
| Outlook/Hotmail | smtp-mail.outlook.com | 465 | 587 | 支援 OAuth2 |
| 163/126 | smtp.163.com | 465/994 | 25/587 | 需在網頁端開啟 SMTP 服務獲取授權碼 |
| QQ 郵箱 | smtp.qq.com | 465 | 587 | 需生成授權碼 |
| SendGrid | smtp.sendgrid.net | 465 | 587 | API Key 作為密碼,用戶名固定為 apikey |
| Mailgun | smtp.mailgun.org | 465 | 587 | 需驗證域名 |
| Amazon SES | email-smtp.region.amazonaws.com | 465 | 587 | 需申請移出沙箱 |
對於高並發、高送達率需求,建議直接呼叫 HTTP API:
POST /v3/mail/send,免費額度 100/天POST /v3/yourdomain/messages,免費額度 5,000/月<?php
// SendGrid API 範例
function sendViaSendGrid(string $apiKey, array $params): bool
{
$url = 'https://api.sendgrid.com/v3/mail/send';
$data = [
'personalizations' => [[
'to' => [['email' => $params['to']]],
'subject' => $params['subject'],
]],
'from' => ['email' => $params['from_email'], 'name' => $params['from_name']],
'content' => [[
'type' => 'text/html',
'value' => $params['html'],
]],
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode === 202;
}
?>
| 問題 | 原因 | 解決 |
|---|---|---|
| 連線逾時 | 防火牆封鎖 25/465/587 埠 | 使用 587 TLS 或 465 SSL;檢查安全群組/防火牆 |
| 認證失敗 | 密碼錯誤/未開啟 SMTP | 使用授權碼/應用程式密碼;在郵箱設定開啟 SMTP |
| 進垃圾箱 | 缺 SPF/DKIM/DMARC、IP 信譽差 | 配置域名 DNS 記錄;使用專業郵件服務商 |
| 中文亂碼 | 編碼不一致 | 統一 UTF-8;設定 CharSet、headers 正確 |
| 大量發送被封 | 觸發頻率限制 | 使用佇列限流;分批發送;遷移至 API 服務 |
<?php
// Laravel 隊列 Job 範例
class SendEmailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $tries = 3;
public $backoff = [60, 300, 900]; // 1分、5分、15分重試
public function __construct(
public string $to,
public string $subject,
public string $html,
public array $attachments = []
) {}
public function handle(Mailer $mailer)
{
$mailer->send(new GenericMail($this->to, $this->subject, $this->html, $this->attachments));
}
}
// 控制器中分發
SendEmailJob::dispatch($user->email, '歡迎註冊', $htmlContent)
->onQueue('emails');
?>
核心原則:絕不在 HTTP 請求中同步發送郵件,務必異步佇列化,並建立完善的發送日誌、退信追蹤、送達率監控體系。