亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHPMAILER 將電子郵件配置分離到不同的功能中

PHPMAILER 將電子郵件配置分離到不同的功能中

PHP
弒天下 2022-08-19 16:43:48
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 = '[email protected]';    $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 = '[email protected]';    $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 = '[email protected]';    $mail->Password = 'password';}并在其他郵件程序函數中調用它:function continuedInquiry() {    emailConfig();    /**      *rest of the phpmailer code    */    $mail->send();    notify();}//and so on但是我不斷收到一個錯誤,說$mail沒有定義:我嘗試過返回,我嘗試過爭論。這將簡化事情,但我無法讓它工作。
查看完整描述

1 回答

?
九州編程

TA貢獻1785條經驗 獲得超4個贊

您可能會發現使用子類來配置它更容易,如下所示:


<?php


use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\SMTP;


class myMailer extends PHPMailer

{

    public function __construct($exceptions = null)

    {

        $this->isSMTP();

        $this->SMTPDebug = SMTP::DEBUG_OFF;

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

        $this->Port = 587;

        $this->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

        $this->SMTPAuth = true;

        $this->Username = '[email protected]';

        $this->Password = 'password';

        parent::__construct($exceptions);

    }

}

然后在腳本中,您可以執行以下操作:


$mail = new myMailer(true);

它將完成所有配置,隨時可以使用。


也就是說,最好將“機密”(如密碼)從代碼中移出到外部環境變量或配置文件中,這樣您就不會最終將密碼推送到 git 存儲庫中。


查看完整回答
反對 回復 2022-08-19
  • 1 回答
  • 0 關注
  • 113 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號