本文目录导读:

我来为您详细介绍PHP实现邮件告警的几种方式:
使用 PHP 内置 mail() 函数
基础配置
<?php
// 设置邮件参数
$to = "alerts@example.com";
$subject = "系统告警通知";
$message = "警告:服务器CPU使用率超过90%!";
$headers = "From: monitor@example.com\r\n";
$headers .= "Reply-To: monitor@example.com\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
// 发送邮件
if(mail($to, $subject, $message, $headers)) {
echo "告警邮件发送成功";
} else {
echo "邮件发送失败";
}
?>
配置 php.ini(Linux)
SMTP = smtp.example.com smtp_port = 25 sendmail_from = monitor@example.com
使用 PHPMailer 库(推荐)
安装 PHPMailer
composer require phpmailer/phpmailer
完整的告警邮件类
<?php
require_once 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
class AlertMailer {
private $mail;
public function __construct() {
$this->mail = new PHPMailer(true);
// 服务器配置
$this->mail->SMTPDebug = SMTP::DEBUG_OFF; // 生产环境设为OFF
$this->mail->isSMTP();
$this->mail->Host = 'smtp.example.com';
$this->mail->SMTPAuth = true;
$this->mail->Username = 'alerts@example.com';
$this->mail->Password = 'your-password';
$this->mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$this->mail->Port = 587;
// 通用设置
$this->mail->setFrom('alerts@example.com', '系统监控');
$this->mail->CharSet = 'UTF-8';
$this->mail->isHTML(true);
}
public function sendSystemAlert($severity, $message, $details = '') {
try {
// 收件人
$this->mail->addAddress('admin@example.com', '管理员');
// 根据严重级别设置不同主题
$subjectMap = [
'info' => '[信息] 系统通知',
'warning' => '[警告] 系统异常提醒',
'error' => '[严重] 系统故障!',
'critical' => '[紧急] 系统崩溃!'
];
$this->mail->Subject = $subjectMap[$severity] ?? '系统告警';
// HTML邮件内容
$htmlContent = "
<html>
<head>
<style>
.alert { padding: 15px; margin: 10px 0; border-radius: 5px; }
.info { background: #d1ecf1; color: #0c5460; }
.warning { background: #fff3cd; color: #856404; }
.error { background: #f8d7da; color: #721c24; }
.critical { background: #dc3545; color: white; }
</style>
</head>
<body>
<h2>系统监控告警</h2>
<div class='alert {$severity}'>
<h3>{$subjectMap[$severity]}</h3>
<p><strong>时间:</strong>" . date('Y-m-d H:i:s') . "</p>
<p><strong>消息:</strong>{$message}</p>
<p><strong>详情:</strong>{$details}</p>
</div>
<hr>
<p>此邮件由系统自动发送,请勿回复。</p>
</body>
</html>
";
$this->mail->Body = $htmlContent;
$this->mail->AltBody = strip_tags($message); // 纯文本版本
$this->mail->send();
return ['success' => true, 'message' => '邮件发送成功'];
} catch (Exception $e) {
return ['success' => false, 'message' => $this->mail->ErrorInfo];
}
}
// 重置邮件实例
public function clearAddresses() {
$this->mail->clearAddresses();
$this->mail->clearAttachments();
}
}
// 使用示例
$alertMailer = new AlertMailer();
$result = $alertMailer->sendSystemAlert(
'warning',
'服务器可用内存不足',
"当前内存使用: 92%\n服务器IP: 192.168.1.100\n进程数: 235"
);
echo $result['message'];
?>
使用 SwiftMailer 库
安装
composer require swiftmailer/swiftmailer
实现示例
<?php
require_once 'vendor/autoload.php';
class SwiftAlertMailer {
private $mailer;
public function __construct() {
// 创建Transport
$transport = (new Swift_SmtpTransport('smtp.example.com', 587, 'tls'))
->setUsername('alerts@example.com')
->setPassword('your-password');
// 创建Mailer
$this->mailer = new Swift_Mailer($transport);
}
public function sendAlert($subject, $body) {
// 创建消息
$message = (new Swift_Message($subject))
->setFrom(['alerts@example.com' => '系统监控'])
->setTo(['admin@example.com', 'ops@example.com'])
->setBody($body, 'text/html')
->addPart(strip_tags($body), 'text/plain');
// 发送
$result = $this->mailer->send($message);
return $result > 0;
}
}
通用告警类(支持多种渠道)
<?php
class AlertManager {
private $config;
private $mailer;
public function __construct() {
$this->config = [
'email' => [
'enabled' => true,
'to' => ['admin@example.com'],
'from' => 'monitor@example.com'
],
'sms' => [
'enabled' => false,
'api_key' => 'your-api-key'
],
'webhook' => [
'enabled' => true,
'url' => 'https://hooks.slack.com/services/xxx'
]
];
}
public function sendAlert($type, $message, $context = []) {
$results = [];
switch ($type) {
case 'cpu_high':
$results[] = $this->emailAlert('CPU告警', $message);
$results[] = $this->webhookAlert('CPU告警', $message);
break;
case 'disk_full':
$results[] = $this->emailAlert('磁盘告警', $message);
break;
case 'service_down':
$results[] = $this->emailAlert('服务告警', $message);
$results[] = $this->smsAlert($message);
break;
}
return $results;
}
private function emailAlert($subject, $message) {
if (!$this->config['email']['enabled']) {
return false;
}
// 使用PHPMailer发送
$mail = new PHPMailer(true);
// ... 配置代码同上
return $mail->send();
}
private function webhookAlert($subject, $message) {
if (!$this->config['webhook']['enabled']) {
return false;
}
$data = json_encode([
'text' => "⚠️ *{$subject}*\n{$message}",
'channel' => '#alerts'
]);
$ch = curl_init($this->config['webhook']['url']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_exec($ch);
curl_close($ch);
}
}
实际应用场景示例
系统监控告警
<?php
class SystemMonitor {
private $alertMailer;
private $thresholds = [
'cpu' => 90,
'memory' => 85,
'disk' => 90
];
public function __construct() {
$this->alertMailer = new AlertMailer();
}
public function checkSystem() {
$issues = [];
// 检查CPU
$cpuUsage = $this->getCpuUsage();
if ($cpuUsage > $this->thresholds['cpu']) {
$issues[] = "CPU使用率: {$cpuUsage}%";
}
// 检查内存
$memoryUsage = $this->getMemoryUsage();
if ($memoryUsage > $this->thresholds['memory']) {
$issues[] = "内存使用率: {$memoryUsage}%";
}
// 检查磁盘
$diskUsage = $this->getDiskUsage();
if ($diskUsage > $this->thresholds['disk']) {
$issues[] = "磁盘使用率: {$diskUsage}%";
}
// 发送告警
if (!empty($issues)) {
$this->alertMailer->sendSystemAlert(
'warning',
'系统资源告警',
"服务器: " . gethostname() . "\n" . implode("\n", $issues)
);
}
}
private function getCpuUsage() {
// 实现获取CPU使用率
return 95; // 示例数据
}
private function getMemoryUsage() {
return 80;
}
private function getDiskUsage() {
return 75;
}
}
// 定时运行
$monitor = new SystemMonitor();
$monitor->checkSystem();
配置文件示例
config.php
<?php
return [
'email' => [
'host' => 'smtp.gmail.com',
'port' => 587,
'encryption' => 'tls',
'username' => 'alert@yourcompany.com',
'password' => 'your-app-password',
'from_address' => 'alert@yourcompany.com',
'from_name' => '系统监控',
'to_addresses' => [
'admin@example.com',
'ops@example.com'
]
],
'alert_thresholds' => [
'cpu' => 90,
'memory' => 85,
'disk' => 90,
'error_rate' => 50
],
'retry' => [
'max_attempts' => 3,
'delay_seconds' => 60
]
];
最佳实践建议
- 使用队列系统:避免请求阻塞
- 实现重试机制:失败时自动重试
- 设置发送频率限制:防止告警风暴
- 日志记录:记录所有告警历史
- 分级告警:根据严重级别设置不同渠道
- 测试模式:开发环境不实际发送
这样的实现可以满足大多数PHP邮件告警需求,实际使用时,建议优先选择PHPMailer这类成熟库,内置更多功能和异常处理。