ubuntu

Ubuntu下PHP如何配置邮件发送功能

小樊
36
2025-11-26 20:19:25
栏目: 编程语言

在 Ubuntu 下配置 PHP 邮件发送功能,通常需要以下几个步骤:

  1. 安装 PHP 邮件发送库

在终端中运行以下命令来安装 PHP 的邮件发送库(例如 PHPMailer):

sudo apt-get update
sudo apt-get install php-mailer
  1. 配置 PHP 邮件发送参数

编辑 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.comsmtp_portyour-email@example.comyour-email-password 替换为你的 SMTP 服务器信息和邮箱账户信息。

  1. 重启 Web 服务器

保存 php.ini 文件后,重启 Web 服务器以使更改生效。如果你使用的是 Apache,可以运行以下命令:

sudo systemctl restart apache2

如果你使用的是 Nginx,可以运行以下命令:

sudo systemctl restart nginx
  1. 测试邮件发送功能

创建一个 PHP 文件(例如 test_email.php),并添加以下代码:

<?php
$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->SMTPDebug = 2;
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->AuthType = 'LOGIN';
    $mail->Port = 587;
    $mail->SMTPSecure = 'tls';
    $mail->setFrom('your-email@example.com', 'Mailer');
    $mail->addAddress('recipient@example.com', 'Recipient Name'); // Add a recipient

    // Content
    $mail->isHTML(true);
    $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.comyour-email@example.comrecipient@example.com 替换为你的 SMTP 服务器信息和邮箱账户信息。然后,在浏览器中访问 test_email.php 文件,如果配置正确,你应该能看到邮件发送成功的消息。

注意:在实际部署时,请确保使用安全的方式存储和传输敏感信息(如邮箱密码)。

0
看了该问题的人还看了