PHPMAILER 将电子邮件配置分离到不同的功能中

PHPMAILER在我的网站上工作正常。我想做的是将配置部分分成一个单独的函数,这样当我创建不同的响应电子邮件时,我需要做的就是在不同的响应函数中调用该函数。emailConfig()


function continuedInquiry() {

    //config portion I want to separate

    $mail = new PHPMailer;

    $mail->isSMTP();

    $mail->SMTPDebug = SMTP::DEBUG_OFF;

    $mail->Host = 'smtp.gmail.com';

    $mail->Port = 587;

    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

    $mail->SMTPAuth = true;

    $mail->Username = 'example@gmail.com';

    $mail->Password = 'password';


    /**

      *rest of the phpmailer code

    */

    $mail->send();


    notify();

}


function notify() {


    //notification email

    $mail = new PHPMailer;

    $mail->isSMTP();

    $mail->SMTPDebug = SMTP::DEBUG_OFF;

    $mail->Host = 'smtp.gmail.com';

    $mail->Port = 587;

    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

    $mail->SMTPAuth = true;

    $mail->Username = 'example@gmail.com';

    $mail->Password = 'password';


    /**

      *rest of the phpmailer code

     */

}

这按预期工作,但是因为我使用的是多个邮件程序,因此我想将配置部分分成一个单独的函数,如下所示:emailConfig()


function emailConfig() {

    $mail = new PHPMailer;

    $mail->isSMTP();

    $mail->SMTPDebug = SMTP::DEBUG_OFF;

    $mail->Host = 'smtp.gmail.com';

    $mail->Port = 587;

    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

    $mail->SMTPAuth = true;

    $mail->Username = 'example@gmail.com';

    $mail->Password = 'password';

}

并在其他邮件程序函数中调用它:


function continuedInquiry() {

    emailConfig();


    /**

      *rest of the phpmailer code

    */

    $mail->send();


    notify();

}


//and so on

但是我不断收到一个错误,说$mail没有定义:

http://img2.mukewang.com/62ff4d5f0001d93c08000137.jpg

我尝试过返回,我尝试过争论。这将简化事情,但我无法让它工作。


弑天下
浏览 100回答 1
1回答

九州编程

您可能会发现使用子类来配置它更容易,如下所示:<?phpuse PHPMailer\PHPMailer\PHPMailer;use PHPMailer\PHPMailer\SMTP;class myMailer extends PHPMailer{&nbsp; &nbsp; public function __construct($exceptions = null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->isSMTP();&nbsp; &nbsp; &nbsp; &nbsp; $this->SMTPDebug = SMTP::DEBUG_OFF;&nbsp; &nbsp; &nbsp; &nbsp; $this->Host = 'smtp.gmail.com';&nbsp; &nbsp; &nbsp; &nbsp; $this->Port = 587;&nbsp; &nbsp; &nbsp; &nbsp; $this->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;&nbsp; &nbsp; &nbsp; &nbsp; $this->SMTPAuth = true;&nbsp; &nbsp; &nbsp; &nbsp; $this->Username = 'example@gmail.com';&nbsp; &nbsp; &nbsp; &nbsp; $this->Password = 'password';&nbsp; &nbsp; &nbsp; &nbsp; parent::__construct($exceptions);&nbsp; &nbsp; }}然后在脚本中,您可以执行以下操作:$mail = new myMailer(true);它将完成所有配置,随时可以使用。也就是说,最好将“机密”(如密码)从代码中移出到外部环境变量或配置文件中,这样您就不会最终将密码推送到 git 存储库中。
打开App,查看更多内容
随时随地看视频慕课网APP