PHP郵件發(fā)送主要有兩種方法:使用PHP的內(nèi)置函數(shù)mail()
和使用第三方庫PHPMailer。
mail()
:mail()
函數(shù)是PHP中用于發(fā)送郵件的內(nèi)置函數(shù)。它不需要額外的庫支持,但功能相對(duì)有限。以下是使用mail()
函數(shù)發(fā)送郵件的基本步驟:
$to = "recipient@example.com";
$subject = "郵件主題";
$message = "郵件內(nèi)容";
$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 "郵件發(fā)送成功";
} else {
echo "郵件發(fā)送失敗";
}
PHPMailer是一個(gè)功能強(qiáng)大的第三方郵件發(fā)送庫,支持多種郵件協(xié)議(如SMTP、sendmail、QQ郵箱等)和郵件服務(wù)提供商。以下是使用PHPMailer發(fā)送郵件的基本步驟:
首先,通過Composer安裝PHPMailer:
composer require phpmailer/phpmailer
然后,使用以下代碼發(fā)送郵件:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// 服務(wù)器設(shè)置
$mail->isSMTP(); // 使用SMTP
$mail->Host = 'smtp.example.com'; // SMTP服務(wù)器地址
$mail->SMTPAuth = true; // 啟用SMTP認(rèn)證
$mail->Username = 'your_username'; // SMTP用戶名
$mail->Password = 'your_password'; // SMTP密碼
$mail->SMTPSecure = 'tls'; // 啟用TLS加密
$mail->Port = 587; // SMTP端口
// 發(fā)件人和收件人
$mail->setFrom('sender@example.com', 'Sender Name');
$mail->addAddress('recipient@example.com', 'Recipient Name'); // 收件人郵箱
// 郵件內(nèi)容
$mail->isHTML(true); // 設(shè)置郵件格式為HTML
$mail->Subject = '郵件主題';
$mail->Body = '郵件內(nèi)容';
$mail->send();
echo '郵件發(fā)送成功';
} catch (Exception $e) {
echo "郵件發(fā)送失敗。Mailer Error: {$mail->ErrorInfo}";
}
?>
這兩種方法都可以實(shí)現(xiàn)PHP郵件發(fā)送,但PHPMailer提供了更多的功能和更好的兼容性,因此推薦使用PHPMailer。