在 PHPMailer 中使用全局变量

Using global variables in PHPMailer

而不是这个:

$mail->isSMTP();  
$mail->Host = 'smtp.demo-server.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 'demo-port';
$mail->Username = 'demo-email@gmail.com'; 
$mail->Password = 'demo-password';

我想将这些值保存在一个单独的文件中并改用变量:

$mail->isSMTP();  
$mail->Host = echo $server; // also tried without echo
$mail->SMTPAuth = true;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = echo $port;
$mail->Username = echo $username; 
$mail->Password = echo $password;

我已经在使用输出缓冲,设置了全局范围,并且变量值包含引号。还是不行。

首先,请阅读 @Synchro 的评论。

  • 如果您还没有创建一个 php 文件(例如 mail_config.php)并在其中声明您的变量。
  • Require/Include“主”文件中的 mail_config.php 文件(发送邮件的文件,例如 send_mail.php)。
  • 将 PHPMailer 道具分配给它们各自的变量 mail_config.php 文件在 send_mail.php 文件中。

例子

mail_config.php

<?php

$server   = 'smtp.gmail.com';
$port     = 465;
$username = 'test@gmail.com';
$password = '123456';

?>

send_mail.php

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// require the settings file. This contains the settings
require 'path/to/mail_config.php';

// require the vendor/autoload.php file if you're using Composer
require 'path/to/vendor/autoload.php';

// require phpmailer files if you're not using Composer
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host          = $server;
    $mail->SMTPAuth      = true;
    $mail->SMTPSecure    = PHPMailer::ENCRYPTION_SMTPS; // 'ssl'
    $mail->Port          = $port;
    $mail->Username      = $username;
    $mail->Password      = $password;

    $mail->setFrom('from@example.com', "Sender's Name"); // sender's email(mostly the `$username`) and name.
    $mail->addAddress('test@example.com', 'Whosebug'); // recipient email and optional name.

    //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->send();
    echo 'Message has been sent';
} catch(Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

?>

阅读更多https://github.com/PHPMailer/PHPMailer