溫馨提示×

Ubuntu PHP配置SMTP郵件發送方法

小樊
52
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服務器和憑據:

  • smtp.example.com:您的SMTP服務器地址
  • your-email@example.com:您的電子郵件地址
  • your-app-password:您的應用程序密碼(如果您的SMTP服務器支持OAuth2)
  1. 運行腳本:

在終端中,導航到包含send_email.php文件的目錄,并運行以下命令:

php send_email.php

如果一切正常,您應該會看到“Message has been sent”的消息。如果出現錯誤,請檢查錯誤消息以獲取有關問題的詳細信息。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女