當前位置: 首頁> 最新文章列表> 如何使用PHP發送郵件:完整教程與示例代碼

如何使用PHP發送郵件:完整教程與示例代碼

gitbox 2025-07-15

在網絡應用中,郵件發送功能常常被用來實現用戶註冊驗證、自動化通知等功能。 PHP作為一種高效且廣泛使用的腳本語言,提供了多種方法來實現郵件發送。本文將通過簡單的代碼示例,帶您學習如何在PHP中發送郵件。

為什麼選擇PHP發送郵件

PHP提供了內置的mail()函數,能夠幫助開發者輕鬆發送郵件。 PHP的靈活性和廣泛支持的服務器環境,使其成為發送郵件的理想選擇。通過PHP,您可以快速實現通知、反饋、驗證等郵件發送需求。

PHP郵件發送的基本設置

為了確保郵件發送的順利進行,您需要配置您的服務器環境。一般而言,您需要完成以下兩個步驟:

  • 啟用PHP的mail()函數。
  • 配置服務器的郵件服務,特別是SMTP設置。

使用mail()函數發送郵件

PHP內置的mail()函數非常適合用於簡單的郵件發送場景。以下是一個基本的使用示例:

 $to = '[email protected]';
$subject = 'Test Email';
$message = 'This is a test email sent using PHP mail function.';
$headers = 'From: [email protected]' . "\r\n" . 'Reply-To: [email protected]' . "\r\n" . 'X-Mailer: PHP/' . phpversion();

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

使用PHPMailer發送郵件

PHPMailer是一個功能強大的郵件發送庫,提供了比mail()函數更靈活的功能,特別是支持SMTP服務器和HTML郵件的發送。以下是使用PHPMailer發送郵件的步驟:

安裝PHPMailer

您可以通過Composer安裝PHPMailer庫。請運行以下命令:

 composer require phpmailer/phpmailer

使用PHPMailer發送郵件的示例代碼

以下是使用PHPMailer發送郵件的代碼示例:

 use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';

$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'yourpassword';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    $mail->setFrom('[email protected]', 'Mailer');
    $mail->addAddress('[email protected]', 'Joe User');
    $mail->Subject = 'Here is the subject';
    $mail->Body    = '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}";
}

總結

通過本教程,您已經掌握瞭如何使用PHP發送郵件。無論是使用PHP內置的mail()函數,還是通過PHPMailer實現更複雜的郵件發送,都可以輕鬆滿足開發需求。確保配置正確的郵件服務和服務器,能夠提高郵件發送的成功率。如果您遇到問題,可以參考相關文檔,或在社區中尋找幫助。