如何用PHP发送电子邮件?

2025-12发布14次浏览

在PHP中发送电子邮件,你可以使用内置的mail()函数,它是一个简单的函数,适合基本的邮件发送需求。不过,mail()函数的配置和可靠性依赖于服务器的邮件发送设置,因此,对于更高级的邮件发送需求,你可能需要使用第三方库,如PHPMailer或SwiftMailer。

以下是使用mail()函数发送电子邮件的基本步骤:

  1. 设置邮件的接收者。
  2. 设置邮件的标题。
  3. 设置邮件正文。
  4. 设置邮件的额外头信息,如发件人。
  5. 调用mail()函数发送邮件。

下面是一个使用mail()函数的简单示例:

<?php
$to = 'recipient@example.com'; // 收件人邮箱地址
$subject = 'Test Email'; // 邮件主题
$message = 'This is a test email sent from a PHP script.'; // 邮件正文
$headers = 'From: sender@example.com' . "\r\n" .
    'Reply-To: sender@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion(); // 邮件头信息

if (mail($to, $subject, $message, $headers)) {
    echo 'Email sent successfully.';
} else {
    echo 'Email sending failed.';
}
?>

在使用mail()函数时,确保你的服务器已经正确配置了邮件发送服务,否则邮件可能无法成功发送。

对于更高级的邮件发送需求,如HTML邮件、附件、SMTP认证等,推荐使用PHPMailer或类似的库。这些库提供了更多的功能和更好的错误处理机制。

// 使用PHPMailer的示例(需要下载并包含PHPMailer类文件)

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';

$mail = new PHPMailer(true);

try {
    // 服务器设置
    $mail->isSMTP();                                      // 设置使用SMTP
    $mail->Host       = 'smtp.example.com';               // 设置SMTP服务器地址
    $mail->SMTPAuth   = true;                             // 启用SMTP认证
    $mail->Username   = 'user@example.com';               // SMTP 用户名
    $mail->Password   = 'password';                       // SMTP 密码
    $mail->SMTPSecure = 'tls';                            // 启用TLS加密
    $mail->Port       = 587;                              // TCP端口

    // 收件人
    $mail->setFrom('sender@example.com', 'Mailer');
    $mail->addAddress('recipient@example.com', 'Recipient Name');     // 添加一个收件人

    // 内容设置
    $mail->isHTML(true);                                  // 设置邮件格式为HTML
    $mail->Subject = 'Here is the subject';                // 邮件主题
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>'; // 邮件正文
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; // 邮件纯文本正文

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>

确保替换示例中的占位符,如服务器设置、发件人、收件人等信息,以匹配你的实际配置。