SMTP(簡單郵件傳輸協議)是互聯網中負責郵件傳遞的標準協議。通過SMTP協議,PHP開發者可以實現郵件的發送,支持文本、附件甚至圖片等內容的發送功能。
PHPMailer是PHP中廣泛使用的郵件發送類庫,支持SMTP協議及多種郵件格式。安裝PHPMailer可以通過Composer,命令如下:
<span class="fun">composer require phpmailer/phpmailer</span>
安裝完成後,在PHP腳本中引入自動加載文件,以便使用PHPMailer類:
<span class="fun">require 'vendor/autoload.php';</span>
創建PHPMailer對象並設置SMTP服務器相關信息,包括服務器地址、認證信息和加密方式:
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your-password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
請根據實際情況替換以上參數中的SMTP服務器地址、用戶名和密碼。
指定發件人、收件人、郵件主題和正文內容:
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email.';
調用PHPMailer的send()方法執行郵件發送操作,並根據結果進行提示:
if ($mail->send()) {
echo 'Email sent successfully.';
} else {
echo 'Email sending failed. Error: ' . $mail->ErrorInfo;
}
require 'vendor/autoload.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your-password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email.';
if ($mail->send()) {
echo 'Email sent successfully.';
} else {
echo 'Email sending failed. Error: ' . $mail->ErrorInfo;
}
本文介紹瞭如何使用PHPMailer庫在PHP中通過SMTP協議發送郵件,包含從安裝庫、引入類、配置SMTP參數到設置郵件內容及發送的完整步驟。掌握這些內容後,您可以靈活地將郵件功能集成到自己的PHP項目中。