温馨提示×

PHP在Linux上如何配置SMTP邮件发送

小樊
45
2025-10-29 00:39:27
栏目: 编程语言

在Linux上配置PHP以通过SMTP发送邮件,通常需要以下几个步骤:

  1. 安装和配置邮件传输代理(MTA): 你可以使用postfixsendmailexim等MTA。这里以postfix为例。

    sudo apt-get update
    sudo apt-get install postfix
    

    在安装过程中,选择“Internet Site”作为配置类型,并设置系统邮件名称。

  2. 配置PHPMailer: PHPMailer是一个流行的PHP库,用于发送电子邮件。你可以通过Composer来安装它。

    composer require phpmailer/phpmailer
    
  3. 编写PHP脚本: 创建一个PHP脚本来发送邮件。以下是一个简单的示例:

    <?php
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    
    require 'vendor/autoload.php';
    
    mailer = new PHPMailer(true);
    
    try {
        // Server settings
        mailer->SMTPDebug = 2;                                      // Enable verbose debug output
        mailer->isSMTP();                                           // Send using SMTP
        mailer->Host       = 'smtp.example.com';                     // Set the SMTP server to send through
        mailer->SMTPAuth   = true;                                   // Enable SMTP authentication
        mailer->AuthType   = 'XOAUTH2';                              // OAuth2 Authentication
        mailer->Port       = 587;                                    // TCP port to connect to; use 465 for `SMTPS`
        mailer->SMTPSecure = 'tls';                                    // Enable TLS encryption; `SMTPS` also accepted
    
        // OAuth2 credentials
        mailer->OAuthUserEmail = 'your-email@example.com';
        mailer->OAuthClientId  = 'your-client-id';
        mailer->OAuthClientSecret  = 'your-client-secret';
        mailer->OAuthRefreshToken  = 'your-refresh-token';
    
        // Recipients
        mailer->setFrom('from@example.com', 'Mailer');
        mailer->addAddress('recipient@example.com', 'Joe User');     // Add a recipient
    
        // Content
        mailer->isHTML(true);                                        // Set email format to HTML
        mailer->Subject = 'Here is the subject';
        mailer->Body    = 'This is the HTML message body <b>in bold!</b>';
        mailer->AltBody = 'This is the body in plain text for non-HTML mail clients';
    
        mailer->send();
        echo 'Message has been sent';
    } catch (Exception $e) {
        echo "Message could not be sent. Mailer Error: {$mailer->ErrorInfo}";
    }
    
  4. 配置SMTP服务器: 根据你使用的SMTP服务提供商(如Gmail、Outlook等),你需要配置相应的SMTP服务器地址、端口、认证方式和OAuth凭证。

  5. 测试邮件发送: 运行你的PHP脚本,检查是否能够成功发送邮件。

    php your-script.php
    

通过以上步骤,你应该能够在Linux上配置PHP以通过SMTP发送邮件。确保你的SMTP服务器配置正确,并且你有相应的权限和凭证。

0