在CentOS上配置PHP的SMTP郵件可以通過多種方式實現,以下是使用sendmail
和phpMailer
兩種常見方法的詳細步驟。
安裝Sendmail
sudo yum install sendmail sendmail-cf mailx
配置Sendmail
編輯/etc/mail/sendmail.cf
文件,添加SMTP服務器信息:
sudo vi /etc/mail/sendmail.cf
在文件中添加以下內容:
define(`SMART_HOST', `smtp.yourprovider.com')dnl
define(`RELAY_MAILER_ARGS', `TCP $h 587')dnl
define(`ESMTP_MAILER_ARGS', `TCP $h 587')dnl
define(`confAUTH_OPTIONS', `A p')dnl
TRUST_AUTH_MECH(`EXTERNAL DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
重啟Sendmail服務
sudo systemctl restart sendmail
測試Sendmail
echo "Subject: Test Email" | sendmail -v your-email@example.com
安裝PHPMailer 你可以使用Composer來安裝PHPMailer:
composer require phpmailer/phpmailer
編寫PHP腳本
創建一個PHP文件(例如send_email.php
),并添加以下代碼:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
mailer = new PHPMailer(true);
try {
// Server settings
mailer->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
mailer->isSMTP(); // Send using SMTP
mailer->Host = 'smtp.yourprovider.com'; // Set the SMTP server to send through
mailer->SMTPAuth = true; // Enable SMTP authentication
mailer->AuthType = SMTP::AUTH_LOGIN; // Authentication type
mailer->Port = 587; // TCP port to connect to; use 465 for `SMTPS`
mailer->SMTPSecure = SMTP::ENCRYPTION_STARTTLS; // Enable implicit TLS encryption
mailer->Username = 'your-email@example.com'; // SMTP username
mailer->Password = 'your-password'; // SMTP password
mailer->SMTPAutoTLS = true; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
// Recipients
mailer->setFrom('your-email@example.com', 'Mailer');
mailer->addAddress('recipient@example.com', 'Recipient Name'); // Add a recipient
// Content
mailer->isHTML(true); // Set email format to HTML
mailer->Subject = 'Here is the subject';
mailer->Body = 'This is the HTML message body <b>in bold!</b>';
mailer->AltBody = 'This is the body in plain text for non-HTML mail clients';
mailer->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mailer->ErrorInfo}";
}
運行PHP腳本
php send_email.php
通過以上步驟,你應該能夠在CentOS上成功配置PHP的SMTP郵件功能。