溫馨提示×

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

小樊
48
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女