在Ubuntu上使用PHP发送邮件,通常需要配置一个邮件传输代理(MTA),如Postfix或Sendmail。以下是使用PHPMailer库通过SMTP发送邮件的步骤:
安装PHPMailer: 你可以使用Composer来安装PHPMailer。首先,确保你已经安装了Composer。如果没有安装,可以通过以下命令安装:
sudo apt-get install composer
然后,在你的项目目录中运行以下命令来安装PHPMailer:
composer require phpmailer/phpmailer
配置SMTP设置: 在你的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 = SMTP::ENCRYPTION_STARTTLS; // Enable implicit TLS encryption
// Credentials
$mail->OAuthUserEmail = 'your-email@example.com'; // Your email address
$mail->OAuthClientId = 'your-client-id'; // Your OAuth Client ID
$mail->OAuthClientSecret = 'your-client-secret'; // Your OAuth Client Secret
$mail->OAuthRefreshToken = 'your-refresh-token'; // Your OAuth Refresh Token
// Recipients
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('recipient@example.com', 'Joe User'); // 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服务器地址、端口、认证信息和收件人地址为你自己的设置。
测试邮件发送: 运行你的PHP脚本,如果一切配置正确,你应该能够收到一封测试邮件。
请注意,如果你使用的是Gmail或其他流行的邮件服务提供商,你需要创建一个应用专用密码或者启用两步验证并生成一个应用专用密码来代替你的常规密码。此外,确保你的邮件服务器允许通过SMTP发送邮件,并且你的IP地址没有被列入黑名单。
如果你不想使用SMTP,也可以考虑使用PHP的内置mail()
函数来发送邮件,但这通常需要你的服务器已经配置了MTA,并且可能不如使用SMTP可靠。