2026-10-24 15:31:05
PHP 提供了多种方式发送电子邮件,包括内置函数和第三方类库。以下是详细解答:
1. 内置函数mail() 函数需配置服务器的 sendmail 或 SMTP 设置(如 php.ini 中的 SMTP 和 sendmail_path)。
默认不支持 HTML 格式,需通过 $headers 添加 Content-type: text/html。
安装:通过 Composer 或下载源码。composer require phpmailer/phpmailer
示例代码:<?phpuse PHPMailerPHPMailerPHPMailer;require 'vendor/autoload.php';$mail = new PHPMailer(true);try { // SMTP 配置 $mail->isSMTP(); $mail->Host = 'smtp.example.com'; $mail->SMTPAuth = true; $mail->Username = 'your_email@example.com'; $mail->Password = 'your_password'; $mail->SMTPSecure = 'tls'; $mail->Port = 587; // 邮件内容 $mail->setFrom('sender@example.com', 'Sender Name'); $mail->addAddress('recipient@example.com', 'Recipient Name'); $mail->Subject = 'HTML Email'; $mail->Body = '<h1>This is HTML content</h1>'; $mail->AltBody = 'Plain text fallback'; $mail->send(); echo 'Email sent!';} catch (Exception $e) { echo "Error: {$e->getMessage()}";}?>
SMTP 配置:
确保使用可靠的邮件服务(如 Gmail SMTP、SendGrid、Mailgun)。
避免使用共享主机的 SMTP,可能被标记为垃圾邮件。
防垃圾邮件:
设置正确的 From 地址和域名。
避免敏感词汇(如“免费”“优惠”)。
错误处理:
使用 try-catch 捕获异常(如 PHPMailer)。
启用调试模式($mail->SMTPDebug = 2)。
性能优化:
避免在循环中发送邮件,批量处理更高效。
通过以上方法,可以灵活实现 PHP 邮件发送功能。