在 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 以发送邮件。