温馨提示×

如何配置Ubuntu PHP的SMTP邮件功能

小樊
56
2025-06-07 04:57:31
栏目: 编程语言

要在Ubuntu上配置PHP的SMTP邮件功能,您需要使用PHPMailer库。以下是详细步骤:

  1. 安装PHPMailer

首先,您需要在项目中安装PHPMailer。您可以使用Composer来安装它。在项目根目录下运行以下命令:

composer require phpmailer/phpmailer
  1. 创建PHP文件

创建一个新的PHP文件,例如send_email.php,并在其中编写以下代码:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new 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 (LOGIN, PLAIN, CRAM-MD5, DIGEST-MD5, XOAUTH2)
    $mail->Port       = 587;                                    // TCP port to connect to; use 465 for `SMTPS`
    $mail->SMTPSecure = 'tls';                                    // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged

    // Sender and recipient
    $mail->setFrom('from@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}";
}
  1. 配置SMTP服务器设置

在上面的代码中,您需要将以下设置替换为您的SMTP服务器信息:

  • smtp.example.com:您的SMTP服务器地址
  • 587:您的SMTP服务器端口(通常为587或465)
  • tls:您的SMTP服务器加密类型(通常为tlsssl

同时,您还需要提供SMTP服务器的用户名和密码。将以下代码中的your_usernameyour_password替换为您的实际凭据:

$mail->SMTPAuth   = true;
$mail->AuthType   = 'login';
$mail->Username   = 'your_username';
$mail->Password   = 'your_password';
  1. 运行脚本

保存您的send_email.php文件,然后在终端中运行以下命令来发送邮件:

php send_email.php

如果一切配置正确,您应该会看到“Message has been sent”的输出,并且收件人将收到一封电子邮件。

注意:在实际部署中,请确保使用环境变量或其他安全方法存储敏感信息,如SMTP凭据。

0