在Ubuntu上配置PHP以發送SMTP郵件,您可以使用PHPMailer庫
通過Composer安裝PHPMailer。在終端中運行以下命令:
sudo apt-get install composer
composer require phpmailer/phpmailer
在您的項目目錄中創建一個新的PHP文件,例如send_email.php
。
在新創建的PHP文件中,編寫以下代碼以使用PHPMailer發送SMTP郵件:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // 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 (if supported by your server)
$mail->Port = 587; // TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->OAuthUserEmail = 'your-email@example.com'; // Your email address
$mail->OAuthPassword = 'your-app-password'; // Your OAuth2 application password
// Recipients
$mail->setFrom('your-email@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服務器和憑據:
smtp.example.com
:您的SMTP服務器地址your-email@example.com
:您的電子郵件地址your-app-password
:您的應用程序密碼(如果您的SMTP服務器支持OAuth2)在終端中,導航到包含send_email.php
文件的目錄,并運行以下命令:
php send_email.php
如果一切正常,您應該會看到“Message has been sent”的消息。如果出現錯誤,請檢查錯誤消息以獲取有關問題的詳細信息。