在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”的消息。如果出现错误,请检查错误消息以获取有关问题的详细信息。