ubuntu

Ubuntu下PHP如何配置SMTP邮件

小樊
35
2025-07-11 15:41:24
栏目: 编程语言

在Ubuntu下配置PHP以使用SMTP发送邮件,您需要按照以下步骤操作:

  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 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable implicit TLS encryption
    $mail->Username   = 'your_email@example.com';               // SMTP username
    $mail->Password   = 'your_password';                        // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            // Enable explicit TLS encryption

    // Recipients
    $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服务器和帐户信息:

  1. 运行PHP脚本

保存send_email.php文件并通过命令行运行它:

php send_email.php

如果一切正常,您应该会看到“Message has been sent”的消息。如果出现错误,请检查您的SMTP设置以及防火墙和网络连接。

0
看了该问题的人还看了