ubuntu

Ubuntu PHP配置SMTP邮件发送方法

小樊
57
2025-09-02 19:09:07
栏目: 编程语言

在Ubuntu上配置PHP以发送SMTP邮件,您可以使用PHPMailer库

  1. 安装PHPMailer:

通过Composer安装PHPMailer。在终端中运行以下命令:

sudo apt-get install composer
composer require phpmailer/phpmailer
  1. 创建一个新的PHP文件:

在您的项目目录中创建一个新的PHP文件,例如send_email.php

  1. 编写代码:

在新创建的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}";
}
  1. 更新SMTP设置:

将上述代码中的以下部分替换为您的SMTP服务器和凭据:

  1. 运行脚本:

在终端中,导航到包含send_email.php文件的目录,并运行以下命令:

php send_email.php

如果一切正常,您应该会看到“Message has been sent”的消息。如果出现错误,请检查错误消息以获取有关问题的详细信息。

0
看了该问题的人还看了