在 Ubuntu 下配置 PHP 以發送郵件,通常需要以下幾個步驟:
下面詳細介紹這些步驟:
Ubuntu 默認使用 PHPMailer 庫來發送郵件。你可以使用以下命令安裝 PHPMailer:
sudo apt-get update
sudo apt-get install php-mailer
編輯 PHP 配置文件 php.ini
,設置郵件發送參數。你可以使用以下命令找到 php.ini
文件的位置:
php --ini
在 php.ini
文件中,找到以下參數并進行配置:
[mail function]
; For Win32 only.
SMTP = smtp.example.com
smtp_port = 587
sendmail_from = your-email@example.com
auth_username = your-email@example.com
auth_password = your-email-password
將 smtp.example.com
、smtp_port
、your-email@example.com
和 your-email-password
替換為你的 SMTP 服務器地址、端口、郵箱地址和密碼。
創建一個 PHP 文件(例如 send_email.php
),并編寫以下代碼進行郵件發送測試:
<?php
require 'vendor/autoload.php';
$mail = new PHPMailer\PHPMailer\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 = 'LOGIN'; // Authentication type (e.g., LOGIN, PLAIN, CRAM-MD5)
$mail->Port = 587; // TCP port to connect to; use 587 if you have set `SMTPSecure = php artisan mail:send SMTPSecure=tls`
$mail->SMTPSecure = 'tls'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Username = 'your-email@example.com'; // SMTP username
$mail->Password = 'your-email-password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable implicit TLS encryption
// 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.example.com
、smtp_port
、your-email@example.com
和 your-email-password
替換為你的 SMTP 服務器地址、端口、郵箱地址和密碼。
運行腳本:
php send_email.php
如果一切配置正確,你應該會看到郵件發送成功的消息。
通過以上步驟,你應該能夠在 Ubuntu 下成功配置 PHP 以發送郵件。