在Ubuntu上配置PHP的SMTP郵件發送可以通過多種方式實現,其中最常見的是使用PHPMailer庫。以下是一個詳細的步驟指南:
首先,你需要安裝PHPMailer庫。你可以使用Composer來安裝它。
sudo apt update
sudo apt install composer
然后,在你的項目目錄中運行以下命令來安裝PHPMailer:
composer require phpmailer/phpmailer
在你的項目目錄中創建一個新的PHP文件,例如send_email.php
,并添加以下代碼:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.example.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->AuthType = 'XOAUTH2'; // OAuth2 authentication type
$mail->Port = 587; // TCP port to connect to; use 465 for `SMTPS`
$mail->SMTPSecure = 'tls'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
// OAuth2 credentials
$mail->OAuthUserEmail = 'your-email@example.com';
$mail->OAuthClientId = 'your-client-id';
$mail->OAuthClientSecret = 'your-client-secret';
$mail->OAuthRefreshToken = 'your-refresh-token';
// Recipients
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('recipient@example.com', 'Recipient Name'); // Add a recipient
// Content
$mail->isHTML(true); // Set email format to 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}";
}
?>
在上述代碼中,你需要替換以下占位符:
smtp.example.com
: 你的SMTP服務器地址。your-email@example.com
: 你的電子郵件地址。your-client-id
: 你的OAuth2客戶端ID。your-client-secret
: 你的OAuth2客戶端密鑰。your-refresh-token
: 你的OAuth2刷新令牌。保存文件并在終端中運行以下命令來發送郵件:
php send_email.php
如果一切配置正確,你應該會看到消息“Message has been sent”。
通過以上步驟,你應該能夠在Ubuntu上成功配置PHP的SMTP郵件發送功能。