本文目录导读:

- 使用PHP内置mail()函数(简单但不推荐)
- 使用PHPMailer类库(推荐方案)
- 使用SwiftMailer(另一个流行库)
- 邮件模板功能
- 批量发送功能
- 配置文件管理
- 异步发送(使用队列)
- 安全和最佳实践
- 完整使用示例
- 推荐配置指南
我来详细介绍PHP项目邮箱发送功能的开发实现方案。
使用PHP内置mail()函数(简单但不推荐)
<?php
$to = "recipient@example.com";
$subject = "Test Email";
$message = "Hello! This is a test email.";
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
if(mail($to, $subject, $message, $headers)){
echo "Email sent successfully";
} else {
echo "Email sending failed";
}
?>
使用PHPMailer类库(推荐方案)
1 安装PHPMailer
使用Composer安装:
composer require phpmailer/phpmailer
或手动下载: 从GitHub下载PHPMailer
2 基本使用示例
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
class EmailService {
private $mail;
public function __construct() {
$this->mail = new PHPMailer(true);
// 服务器设置
$this->mail->SMTPDebug = SMTP::DEBUG_SERVER; // 调试模式
$this->mail->isSMTP();
$this->mail->Host = 'smtp.gmail.com'; // SMTP服务器
$this->mail->SMTPAuth = true;
$this->mail->Username = 'your-email@gmail.com';
$this->mail->Password = 'your-app-password'; // Gmail应用专用密码
$this->mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$this->mail->Port = 587;
// 发送者信息
$this->mail->setFrom('your-email@gmail.com', 'Your Name');
$this->mail->addReplyTo('reply@example.com', 'Reply Name');
}
public function sendEmail($to, $subject, $body, $isHTML = true) {
try {
// 收件人
$this->mail->addAddress($to);
// 内容设置
$this->mail->isHTML($isHTML);
$this->mail->Subject = $subject;
$this->mail->Body = $body;
$this->mail->AltBody = strip_tags($body); // 纯文本备用
// 添加附件(可选)
// $this->mail->addAttachment('/path/to/file.pdf', 'document.pdf');
$this->mail->send();
return ['success' => true, 'message' => 'Email sent successfully'];
} catch (Exception $e) {
return ['success' => false, 'message' => $this->mail->ErrorInfo];
}
}
}
// 使用示例
$emailService = new EmailService();
$result = $emailService->sendEmail(
'recipient@example.com',
'Test Subject',
'<h1>Hello!</h1><p>This is a test email.</p>'
);
echo json_encode($result);
?>
使用SwiftMailer(另一个流行库)
<?php
require_once 'vendor/autoload.php';
use Swift_SmtpTransport;
use Swift_Mailer;
use Swift_Message;
// 创建传输
$transport = (new Swift_SmtpTransport('smtp.gmail.com', 587, 'tls'))
->setUsername('your-email@gmail.com')
->setPassword('your-app-password');
// 创建邮件器
$mailer = new Swift_Mailer($transport);
// 创建消息
$message = (new Swift_Message('Test Subject'))
->setFrom(['sender@example.com' => 'Sender Name'])
->setTo(['recipient@example.com' => 'Recipient Name'])
->setBody('Here is the message itself')
->addPart('<h1>HTML content</h1><p>Here is the HTML message</p>', 'text/html');
// 发送
try {
$result = $mailer->send($message);
echo "Email sent successfully";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
邮件模板功能
<?php
class EmailTemplate {
public static function getWelcomeTemplate($username) {
return "
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<style>
body { font-family: Arial, sans-serif; }
.container { max-width: 600px; margin: 0 auto; }
.header { background: #4CAF50; color: white; padding: 20px; }
.content { padding: 20px; background: #f9f9f9; }
</style>
</head>
<body>
<div class='container'>
<div class='header'>
<h2>Welcome to Our Platform!</h2>
</div>
<div class='content'>
<p>Dear {$username},</p>
<p>Thank you for joining us!</p>
<p>Please verify your email address by clicking the link below:</p>
<a href='https://example.com/verify?token=xxxxx'
style='background: #4CAF50; color: white; padding: 10px 20px; text-decoration: none;'>
Verify Email
</a>
</div>
</div>
</body>
</html>";
}
public static function getPasswordResetTemplate($resetLink) {
return "
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<style>
body { font-family: Arial, sans-serif; }
.container { max-width: 600px; margin: 0 auto; }
.content { padding: 20px; }
</style>
</head>
<body>
<div class='container'>
<div class='content'>
<h2>Password Reset Request</h2>
<p>Click the link below to reset your password:</p>
<a href='{$resetLink}'>Reset Password</a>
<p>This link expires in 1 hour.</p>
</div>
</div>
</body>
</html>";
}
}
?>
批量发送功能
<?php
class BulkEmailSender {
private $mailer;
public function __construct($mailer) {
$this->mailer = $mailer;
}
public function sendBulkEmails($recipients, $subject, $template) {
$results = [];
foreach ($recipients as $recipient) {
try {
// 创建新消息实例(避免共享问题)
$message = new PHPMailer(true);
// 复制配置...
$message->addAddress($recipient['email'], $recipient['name']);
$message->Subject = $subject;
$message->Body = str_replace(
['{username}', '{email}'],
[$recipient['name'], $recipient['email']],
$template
);
$message->send();
$results[] = [
'email' => $recipient['email'],
'status' => 'success'
];
// 避免被标记为垃圾邮件
usleep(500000); // 延迟0.5秒
} catch (Exception $e) {
$results[] = [
'email' => $recipient['email'],
'status' => 'failed',
'error' => $e->getMessage()
];
}
}
return $results;
}
}
?>
配置文件管理
<?php
// config/email.php
return [
'smtp' => [
'host' => env('MAIL_HOST', 'smtp.gmail.com'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
],
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'noreply@example.com'),
'name' => env('MAIL_FROM_NAME', 'No Reply'),
],
'options' => [
'timeout' => 30,
'debug' => env('MAIL_DEBUG', false),
]
];
// 使用环境变量
// .env 文件
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_ENCRYPTION=tls
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-app-password
MAIL_FROM_ADDRESS=noreply@example.com
MAIL_FROM_NAME=Your Company Name
?>
异步发送(使用队列)
<?php
// 简单的队列实现
class EmailQueue {
private $db;
public function addToQueue($to, $subject, $body) {
// 将邮件信息存入数据库队列
$stmt = $this->db->prepare(
"INSERT INTO email_queue (to_email, subject, body, status, created_at)
VALUES (?, ?, ?, 'pending', NOW())"
);
return $stmt->execute([$to, $subject, $body]);
}
public function processQueue() {
// 获取待发送的邮件
$pending = $this->db->query(
"SELECT * FROM email_queue WHERE status = 'pending' LIMIT 10"
);
foreach ($pending as $email) {
try {
// 发送邮件
$this->sendEmail($email['to_email'], $email['subject'], $email['body']);
// 更新状态
$this->db->query(
"UPDATE email_queue SET status = 'sent', sent_at = NOW()
WHERE id = {$email['id']}"
);
} catch (Exception $e) {
$this->db->query(
"UPDATE email_queue SET status = 'failed', error = '{$e->getMessage()}'
WHERE id = {$email['id']}"
);
}
}
}
}
?>
安全和最佳实践
1 验证和清理输入
<?php
function validateEmailInput($email, $subject, $message) {
// 验证邮箱格式
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException("Invalid email address");
}
// 防止邮件注入
$subject = strip_tags($subject);
$message = strip_tags($message, '<p><br><b><i><a><img>');
// 防止长标题
if (strlen($subject) > 255) {
throw new InvalidArgumentException("Subject too long");
}
return [
'email' => $email,
'subject' => $subject,
'message' => $message
];
}
?>
2 错误处理
<?php
class EmailException extends Exception {
public function __construct($message, $code = 0, Exception $previous = null) {
parent::__construct($message, $code, $previous);
}
public function logError() {
$logData = [
'timestamp' => date('Y-m-d H:i:s'),
'message' => $this->getMessage(),
'file' => $this->getFile(),
'line' => $this->getLine()
];
file_put_contents('email_errors.log',
json_encode($logData) . PHP_EOL,
FILE_APPEND
);
}
}
// 使用
try {
$emailService->sendEmail($to, $subject, $body);
} catch (EmailException $e) {
$e->logError();
echo "Failed to send email. Please try again later.";
}
?>
完整使用示例
<?php
// email_sender.php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class MailSender {
private $config;
private $mailer;
public function __construct($config) {
$this->config = $config;
$this->initializeMailer();
}
private function initializeMailer() {
$this->mailer = new PHPMailer(true);
$this->mailer->isSMTP();
$this->mailer->Host = $this->config['smtp']['host'];
$this->mailer->SMTPAuth = true;
$this->mailer->Username = $this->config['smtp']['username'];
$this->mailer->Password = $this->config['smtp']['password'];
$this->mailer->SMTPSecure = $this->config['smtp']['encryption'];
$this->mailer->Port = $this->config['smtp']['port'];
$this->mailer->setFrom(
$this->config['from']['address'],
$this->config['from']['name']
);
}
public function sendContactEmail($data) {
try {
$this->mailer->addAddress($this->config['admin_email']);
$this->mailer->Subject = "Contact Form: {$data['subject']}";
$body = "
<h2>Contact Form Submission</h2>
<p><strong>Name:</strong> {$data['name']}</p>
<p><strong>Email:</strong> {$data['email']}</p>
<p><strong>Message:</strong></p>
<p>{$data['message']}</p>
";
$this->mailer->Body = $body;
$this->mailer->AltBody = strip_tags($body);
return $this->mailer->send();
} catch (Exception $e) {
throw new EmailException($this->mailer->ErrorInfo);
}
}
}
// 使用
$config = [
'smtp' => [
'host' => 'smtp.gmail.com',
'port' => 587,
'encryption' => 'tls',
'username' => 'your-email@gmail.com',
'password' => 'your-app-password'
],
'from' => [
'address' => 'noreply@example.com',
'name' => 'Your Website'
],
'admin_email' => 'admin@example.com'
];
$mailSender = new MailSender($config);
try {
$result = $mailSender->sendContactEmail([
'name' => 'John Doe',
'email' => 'john@example.com',
'subject' => 'Question about services',
'message' => 'I am interested in your services...'
]);
echo json_encode(['success' => true, 'message' => 'Email sent']);
} catch (EmailException $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
推荐配置指南
-
Gmail配置:
- 启用2FA验证
- 生成应用专用密码
- 允许不够安全的app(不推荐)
-
SMTP配置建议:
- 使用TLS加密
- 端口587(推荐)或465
- 设置合理的超时时间
-
性能优化:
- 使用队列处理批量邮件
- 实现重试机制
- 监控发送限制
-
测试环境:
- 使用Mailtrap或MailHog测试
- 开发环境禁用实际发送
这种方式可以实现稳定、可靠的邮件发送功能,建议使用PHPMailer或SwiftMailer这样的成熟库,而不是直接使用mail()函数。